Exemple #1
0
        public FrmGroupChat(XmppClient xmppClient, Jid roomJid, string nickname, ListView listContract)
        {
            InitializeComponent();
            local_history = new HistoryTransactionTableAdapter();
            connection = new SqlCeConnection(local_history.Connection.ConnectionString);
            _roomJid = roomJid;
            _xmppClient = xmppClient;
            _nickname = nickname;
            _listContract = listContract;
            fm.XmppClient = FrmLogin.Instance.xmppClient;
            fm.OnFile += fm_OnFile;
            Text = roomJid.User + " Group"; ;
            mm = new MucManager(xmppClient);

            // Setup new Message Callback using the MessageFilter
            _xmppClient.MessageFilter.Add(roomJid, new BareJidComparer(), MessageCallback);

            // Setup new Presence Callback using the PresenceFilter
            _xmppClient.PresenceFilter.Add(roomJid, new BareJidComparer(), PresenceCallback);

            GetLastRow(_xmppClient.Username, _xmppClient.XmppDomain, _roomJid.Bare, out LastDtDB);
            btnHistory.Enabled = false;
            Form.CheckForIllegalCrossThreadCalls = false;
            Instance = this;
        }
Exemple #2
0
        static void Main(string[] args)
        {
            var xmppClient = new XmppClient
                                 {
                                     XmppDomain = "jabber.org",
                                     Username = "******",
                                     Password = "******"
                                 };

            xmppClient.OnRosterEnd += delegate
                                          {
                                              xmppClient.Send(new Message
                                                                  {
                                                                      To = "*****@*****.**",
                                                                      Type = MessageType.chat,
                                                                      Body = "Hello World"
                                                                  });

                                          };
            xmppClient.Open();

            Console.WriteLine("Press return key to exit the application");
            Console.ReadLine();

            xmppClient.Close();
        }
Exemple #3
0
 internal XmppClientContainer(XmppClient xmppClient, SynchronizationContext synchronizationContext)
 {
     _xmppClient = xmppClient;
     _synchronizationContext = synchronizationContext;
     Contacts = new ContactsBindingList();
     _xmppClient.Roster.RosterChanged += Roster_RosterChanged;
 }
Exemple #4
0
        public override Task OnConnected()
        {
            Debug.WriteLine("SignalR Connect: " + Context.ConnectionId);

            if (XmppClients.Count == 0)
                SetLicense();

            if (!XmppClients.ContainsKey(Context.ConnectionId))
            {
                var xmppClient = new XmppClient();

                xmppClient.OnReceiveXml += xmppClient_OnReceiveXml;
                xmppClient.OnSendXml += xmppClient_OnSendXml;

                xmppClient.OnPresence   += xmppClient_OnPresence;
                xmppClient.OnMessage    += xmppClient_OnMessage;
                xmppClient.OnIq         += xmppClient_OnIq;

                xmppClient.OnRosterStart += xmppClient_OnRosterStart;
                xmppClient.OnRosterItem += xmppClient_OnRosterItem;
                xmppClient.OnRosterEnd += xmppClient_OnRosterEnd;

                xmppClient.OnLogin += xmppClient_OnLogin;

                xmppClient.OnClose += xmppClient_OnClose;
                xmppClient.OnBeforeSendPresence += xmppClient_OnBeforeSendPresence;
                xmppClient.OnBeforeSasl += xmppClient_OnBeforeSasl;

                XmppClients.Add(Context.ConnectionId, xmppClient);
            }

            return Clients.All.joined(Context.ConnectionId, DateTime.Now.ToString());
        }
 public FrmHistoryTransaction(XmppClient xmppClient, Jid roomJid, string nickname, bool isGroup)
 {
     InitializeComponent();
     _roomJid = roomJid;
     _xmppClient = xmppClient;
     _nickname = nickname;
     _isGroup = isGroup;
 }
        private XmppManager() {
            xmppClient = new XmppClient();

            xmppClient.OnLogin += OnLogin;
            xmppClient.OnMessage += OnMessage;

            xmppClient.Resource = Guid.NewGuid().ToString();
            xmppClient.SetXmppDomain(domain);
        }
Exemple #7
0
        public FrmPubSub(XmppClient client)
        {
            InitializeComponent();

            XmppClient = client;
            _pm = new PubSubManager(client);

            DiscoServer();
        }
Exemple #8
0
 private void loginButton_Click(object sender, EventArgs e)
 {
     usernameTextBox.Enabled = passwordTextBox.Enabled = cancelButton.Enabled = loginButton.Enabled = false;
     loginProgressLabel.Visible = true;
     var xmppSettings = new XmppClientSettings(JId.Parse(usernameTextBox.Text), passwordTextBox.Text, (a, b, c) => true);
     _xmppClient = new XmppClient(xmppSettings);
     XmppClientContainer = new XmppClientContainer(_xmppClient, SynchronizationContext.Current);
     _xmppClient.ConnectionStateChanged += _xmppClient_ConnectionStateChanged;
     _xmppClient.Connect();
 }
Exemple #9
0
        static void Main(string[] args)
        {
            Console.WriteLine("GET TO DA LOONIES");
            Console.WriteLine("DK, DK, DK, DK");

            bool isAndreasFool = true;

            var client = new XmppClient { };
            var clientDos = new XmppClient { };
        }
        public XmppHandlerBase(XmppClient client)
        {
            this.client = client;

            this.client.OnConnected += this.OnConnected;
            this.client.OnConnectException += this.OnConnectException;
            this.client.OnSocketUnexpectedlyClosed += this.OnSocketUnexpectedlyClosed;
            this.client.OnNewDocument += this.OnNewDocument;
            this.client.OnNewElement += this.OnNewElement;
            this.client.OnDocumentComplete += this.OnDocumentComplete;
            this.client.OnXmlException += this.OnXmlException;
        }
Exemple #11
0
        public FrmChat(Jid jid, XmppClient con, string nickname)
        {
            _jid		= jid;
            _xmppClient = con;
            _nickname	= nickname;

            InitializeComponent();

            Text = "Chat with " + nickname;

            Util.ChatForms.Add(_jid.Bare.ToLower(), this);

            // Setup new Message Callback
            con.MessageFilter.Add(jid, new BareJidComparer(), OnMessage);
        }
Exemple #12
0
        public FrmGroupChat(XmppClient xmppClient, Jid roomJid, string nickname)
        {
            InitializeComponent();

            _roomJid = roomJid;
            _xmppClient = xmppClient;
            _nickname = nickname;

            mm = new MucManager(xmppClient);

            // Setup new Message Callback using the MessageFilter
            _xmppClient.MessageFilter.Add(roomJid, new BareJidComparer(), MessageCallback);

            // Setup new Presence Callback using the PresenceFilter
            _xmppClient.PresenceFilter.Add(roomJid, new BareJidComparer(), PresenceCallback);
        }
Exemple #13
0
        //
        // Public Methods
        //
        public Sensor(string server, string user, string pwd, string node)
        {
            m_user = user;
            m_server = server;
            m_pwd = pwd;
            m_node = node;

            m_xmppClient = new XmppClient();
            m_payload = new SensorPayload();
            m_psItem = new Matrix.Xmpp.PubSub.Item();
            m_psJid = new Jid("pubsub." + m_server);
            m_bReady = false;

            _License();
            Connect();
        }
Exemple #14
0
 public User()
 {
     DefaultShow = Matrix.Xmpp.Show.Chat;
     Enabled = true;
     StorePassword = true;
     DefaultPriority = DEFAULT_PRIORITY;
     Connected = false;
     StoreMessageOnDevice = false;
     Group = DEFAULT_GROUP;
     Resource = "ftr";
     Client = new XmppClient();
     Contacts = new List<Contact>();
     Show = Matrix.Xmpp.Show.None;
     Priority = DEFAULT_PRIORITY;
     Status = DefaultStatus;
     Command = new Commands.Commands(this);
 }
Exemple #15
0
        public FrmVCard(XmppClient xc, Jid jid, bool own)
        {
            InitializeComponent();

            xmppClient = xc;

            if (own)
            {
                Text = "My VCard";
                cmdPublish.Enabled = true;
                GetMyVcard();
            }
            else
            {
                Text = "VCard: " + jid;
                GetVcard(jid);
            }
        }
Exemple #16
0
        public FrmAddUser(Dictionary<string, ListViewGroup> _dictContactGroups, bool isAdd, XmppClient xmppClient)
        {
            InitializeComponent();
            _xmppClient = xmppClient;
            DictContactGroups = _dictContactGroups;
            foreach (var item in DictContactGroups)
            {
                cboGroup.Items.Add(item.Value);
            }

            if (!isAdd)
            {
                txtAddress.Enabled = false;
                rtMessage.Enabled = false;
                btnAdd.Text = "Update";
            }
            _xmppClient.OnIq += new EventHandler<IqEventArgs>(_xmppClient_OnIq);
            txtName.Text = string.Empty;
        }
Exemple #17
0
        public FrmChat(Jid jid, XmppClient con, string nickname)
        {
            _jid = jid;
            _xmppClient = con;
            _nickname = nickname;
            local_history = new HistoryTransactionTableAdapter();
            connection = new SqlCeConnection(local_history.Connection.ConnectionString);
            InitializeComponent();

            Text = "Chat with " + nickname;

            Util.ChatForms.Add(_jid.Bare.ToLower(), this);
            // Setup new Message Callback
            con.MessageFilter.Add(jid, new BareJidComparer(), OnMessage);

            GetLastRow(_xmppClient.Username, _xmppClient.XmppDomain, _jid.Bare, out LastDtDB);

            this.Load += new EventHandler(FrmChat_Load);
            Instance = this;
            Form.CheckForIllegalCrossThreadCalls = false;
        }
Exemple #18
0
        public FrmMain()
        {
            InitializeComponent();
            RegisterCustomElements();
            //frmParent.Show();
            InitContactList();
            xmppClient = FrmLogin.Instance.xmppClient;
            fm.XmppClient = FrmLogin.Instance.xmppClient;
            fm.OnFile += fm_OnFile;
            groupChatToolStripMenuItem.Enabled = false;
            settingToolStripMenuItem.Enabled = false;

            groupChatToolStripMenuItem.Enabled = true;
            settingToolStripMenuItem.Enabled = true;

            this.xmppClient.OnError += new EventHandler<ExceptionEventArgs>(xmppClient_OnError);
            this.xmppClient.OnMessage += new EventHandler<MessageEventArgs>(xmppClient_OnMessage);
            this.xmppClient.OnPrebind += new EventHandler<Matrix.Net.PrebindEventArgs>(xmppClient_OnPrebind);

            this.xmppClient.OnBind += new EventHandler<JidEventArgs>(xmppClient_OnBind);
            this.xmppClient.OnClose += new EventHandler<EventArgs>(xmppClient_OnClose);
            this.xmppClient.OnRosterEnd += new EventHandler<EventArgs>(xmppClient_OnRosterEnd);
            this.xmppClient.OnRosterStart += new EventHandler<EventArgs>(xmppClient_OnRosterStart);
            this.xmppClient.OnRosterItem += new EventHandler<Matrix.Xmpp.Roster.RosterEventArgs>(xmppClient_OnRosterItem);
            this.xmppClient.OnPresence += new EventHandler<PresenceEventArgs>(xmppClient_OnPresence);
            this.xmppClient.OnValidateCertificate += new EventHandler<CertificateEventArgs>(xmppClient_OnValidateCertificate);
            this.xmppClient.OnIq += new EventHandler<IqEventArgs>(xmppClient_OnIq);
            this.xmppClient.OnReceiveXml += new EventHandler<TextEventArgs>(xmppClient_OnReceiveXml);
            this.xmppClient.OnStreamError += new EventHandler<StreamErrorEventArgs>(xmppClient_OnStreamError);
            this.xmppClient.OnSendXml += new EventHandler<TextEventArgs>(xmppClient_OnSendXml);
            this.xmppClient.OnRegister += new EventHandler<EventArgs>(xmppClient_OnRegister);
            this.xmppClient.OnRegisterError += new EventHandler<IqEventArgs>(xmppClient_OnRegisterError);
            this.xmppClient.OnRegisterInformation += new EventHandler<RegisterEventArgs>(xmppClient_OnRegisterInformation);
            this.xmppClient.OnBeforeSendPresence += new EventHandler<PresenceEventArgs>(xmppClient_OnBeforeSendPresence);
            this.Load += new EventHandler(FrmMain_Load);

            this.tabPage4.Visible = false;
        }
Exemple #19
0
        /// <summary>
        /// Handles the incoming messages.
        /// </summary>
        public async Task HandleMessages()
        {
            var memoryStream = new MemoryStream();

            // We only care about messages whilst the websocket connection is open.
            while (XmppClient.State == WebSocketState.Open)
            {
                // Create a buffer and receive messages whilst we haven't reached the end of the message.
                WebSocketReceiveResult result;
                do
                {
                    var messageBuffer = WebSocket.CreateClientBuffer(1024, 16);
                    result = await XmppClient.ReceiveAsync(messageBuffer, CancellationToken.None);

                    memoryStream.Write(messageBuffer.Array, messageBuffer.Offset, result.Count);
                } while (!result.EndOfMessage);

                switch (result.MessageType)
                {
                // If the message type is close, dispose of the client.
                case WebSocketMessageType.Close:
                    await DisposeAsync();

                    break;

                case WebSocketMessageType.Text:
                {
                    // Get the message as a string.
                    var message = Encoding.UTF8.GetString(memoryStream.ToArray());

                    // Load the message as an XML document.
                    var document = new XmlDocument();
                    try { document.LoadXml(message.Trim()); }
                    catch { return; }

                    switch (document.DocumentElement.Name)
                    {
                    case "stream:features":
                        await SendAuth();

                        break;

                    case "success":
                        await SendIq("_xmpp_bind1");

                        break;

                    case "iq":
                        if (document.DocumentElement.GetAttribute("id") == "_xmpp_bind1")
                        {
                            await SendIq("_xmpp_session1");
                        }
                        if (document.DocumentElement.GetAttribute("id") == "_xmpp_session1")
                        {
                            await SendPresence(LastPresence ?? new Presence());
                        }
                        break;

                    case "message":
                        await HandleMessage(document);

                        break;
                    }

                    var args = new MessageEventArgs
                    {
                        MessageType = document.DocumentElement.Name,
                        Document    = document
                    };
                    onMessageReceived(args);
                    break;
                }
                }

                // Re-initialise our memory stream.
                memoryStream = new MemoryStream();
            }
        }
Exemple #20
0
        /// <summary>
        /// Implements support for data forms. Data Forms are defined in the following XEPs:
        ///
        /// XEP-0004: Data Forms:
        /// http://xmpp.org/extensions/xep-0004.html
        ///
        /// XEP-0122: Data Forms Validation:
        /// http://xmpp.org/extensions/xep-0122.html
        ///
        /// XEP-0141: Data Forms Layout
        /// http://xmpp.org/extensions/xep-0141.html
        ///
        /// XEP-0221: Data Forms Media Element
        /// http://xmpp.org/extensions/xep-0221.html
        ///
        /// XEP-0331: Data Forms - Color Field Types
        /// http://xmpp.org/extensions/xep-0331.html
        ///
        /// XEP-0336: Data Forms - Dynamic Forms
        /// http://xmpp.org/extensions/xep-0336.html
        ///
        /// XEP-0348: Signing Forms:
        /// http://xmpp.org/extensions/xep-0348.html
        /// </summary>
        /// <param name="Client">XMPP Client.</param>
        /// <param name="X">Data Form definition.</param>
        /// <param name="OnSubmit">Method called when the form is submitted.</param>
        /// <param name="OnCancel">Method called when the form is cancelled.</param>
        /// <param name="From">From where the form came.</param>
        /// <param name="To">To where the form was sent.</param>
        public DataForm(XmppClient Client, XmlElement X, DataFormEventHandler OnSubmit, DataFormEventHandler OnCancel, string From, string To)
        {
            List <string>  Instructions = new List <string>();
            List <Field>   Fields       = new List <Field>();
            List <Field[]> Records      = new List <Field[]>();
            List <Page>    Pages        = null;

            this.client   = Client;
            this.onSubmit = OnSubmit;
            this.onCancel = OnCancel;
            this.from     = From;
            this.to       = To;

            switch (XML.Attribute(X, "type").ToLower())
            {
            case "cancel":
                this.type = FormType.Cancel;
                break;

            case "form":
                this.type = FormType.Form;
                break;

            case "result":
                this.type = FormType.Result;
                break;

            case "submit":
                this.type = FormType.Submit;
                break;

            default:
                this.type = FormType.Undefined;
                break;
            }

            foreach (XmlNode N in X.ChildNodes)
            {
                switch (N.LocalName)
                {
                case "instructions":
                    Instructions.Add(N.InnerText.Trim());
                    break;

                case "title":
                    this.title = N.InnerText.Trim();
                    break;

                case "field":
                    Field Field = this.ParseField((XmlElement)N, out Media Media);
                    Fields.Add(Field);

                    if (Field.PostBack)
                    {
                        this.containsPostBackFields = true;
                    }

                    if (!string.IsNullOrEmpty(Field.Var))
                    {
                        this.fieldsByVar[Field.Var] = Field;
                    }

                    if (Media != null)
                    {
                        Field = new MediaField(this, Guid.NewGuid().ToString(), string.Empty, false,
                                               null, null, string.Empty, new StringDataType(), new BasicValidation(), Media, string.Empty, false, true, false);
                        Fields.Add(Field);
                        this.fieldsByVar[Field.Var] = Field;
                        this.hasMedia = true;
                    }
                    break;

                case "reported":
                    List <Field> Header = new List <Field>();

                    foreach (XmlNode N2 in N.ChildNodes)
                    {
                        if (N2.LocalName == "field")
                        {
                            Field = this.ParseField((XmlElement)N2, out Media);
                            Header.Add(Field);
                        }
                    }

                    this.header = Header.ToArray();
                    break;

                case "item":
                    List <Field> Record = new List <Field>();

                    foreach (XmlNode N2 in N.ChildNodes)
                    {
                        if (N2.LocalName == "field")
                        {
                            Field = this.ParseField((XmlElement)N2, out Media);
                            Record.Add(Field);
                        }
                    }

                    Records.Add(Record.ToArray());
                    break;

                case "page":
                    if (Pages == null)
                    {
                        Pages = new List <Page>();
                    }

                    Pages.Add(new Page(this, (XmlElement)N));
                    break;
                }
            }

            this.instructions = Instructions.ToArray();
            this.fields       = Fields.ToArray();
            this.records      = Records.ToArray();

            if (this.header == null)
            {
                this.header = new Field[0];
            }

            if (this.hasPages = (Pages != null))
            {
                this.pages = Pages.ToArray();
            }
            else if (this.fields.Length > 0)
            {
                this.pages = new Page[] { new Page(this, this.title, this.fields) }
            }
            ;
            else
            {
                this.pages = new Page[] { new Page(this, this.title, new ReportedReference(this)) }
            };

            if (this.hasMedia)
            {
                Dictionary <string, byte[]> Bob = new Dictionary <string, byte[]>(StringComparer.CurrentCultureIgnoreCase);

                foreach (XmlNode N in X.ParentNode.ChildNodes)
                {
                    if (N is XmlElement E && E.LocalName == "data" && E.NamespaceURI == BobClient.Namespace)
                    {
                        string Cid = XML.Attribute(E, "cid");
                        byte[] Bin = Convert.FromBase64String(E.InnerText);

                        Bob["cid:" + Cid] = Bin;
                    }
                }

                foreach (Field F in this.fields)
                {
                    if (F is MediaField MediaField && MediaField.Media != null)
                    {
                        foreach (KeyValuePair <string, Uri> Uri in MediaField.Media.URIs)
                        {
                            switch (Uri.Value.Scheme.ToLower())
                            {
                            case "cid":
                                if (Bob.TryGetValue(Uri.Value.ToString(), out byte[] Bin))
Exemple #21
0
 /// <summary>
 /// <see cref="AuthenticationMethod.Challenge"/>
 /// </summary>
 public override string Challenge(string Challenge, XmppClient Client)
 {
     return(string.Empty);
 }
Exemple #22
0
        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();

            if (instance == this)
            {
                instance = null;
            }

            if (this.chatServer != null)
            {
                this.chatServer.Dispose();
                this.chatServer = null;
            }

            if (this.bobClient != null)
            {
                this.bobClient.Dispose();
                this.bobClient = null;
            }

            if (this.sensorServer != null)
            {
                this.sensorServer.Dispose();
                this.sensorServer = null;
            }

            if (this.xmppClient != null)
            {
                this.xmppClient.Dispose();
                this.xmppClient = null;
            }

            if (this.minuteTimer != null)
            {
                this.minuteTimer.Dispose();
                this.minuteTimer = null;
            }

#if GPIO
            if (this.gpioPin != null)
            {
                this.gpioPin.Dispose();
                this.gpioPin = null;
            }
#else
            if (this.arduino != null)
            {
                this.arduino.digitalWrite(13, PinState.LOW);
                this.arduino.pinMode(13, PinMode.INPUT);                     // Onboard LED.
                this.arduino.pinMode(9, PinMode.INPUT);                      // Relay.

                this.arduino.Dispose();
                this.arduino = null;
            }

            if (this.arduinoUsb != null)
            {
                this.arduinoUsb.end();
                this.arduinoUsb.Dispose();
                this.arduinoUsb = null;
            }
#endif
            Log.Terminate();

            deferral.Complete();
        }
 public XmppConnection()
 {
     m_server = null;
     m_user = null;
     m_pwd = null;
     m_xc = null;
 }
Exemple #24
0
        private void ContractsClient_IdentityUpdated(object Sender, LegalIdentityEventArgs e)
        {
            StringBuilder Markdown = new StringBuilder();

            Markdown.AppendLine("Legal identity updated:");
            Markdown.AppendLine();
            Output(XmppClient.GetBareJID(e.To), Markdown, e.Identity.GetTags());

            MainWindow.currentInstance.Dispatcher.BeginInvoke(new ThreadStart(() =>
            {
                MainWindow.currentInstance.ChatMessage(XmppClient.GetBareJID(e.From), XmppClient.GetBareJID(e.To),
                                                       Markdown.ToString(), true);
            }));
        }
Exemple #25
0
 /// <summary>
 /// Implements a Proxy resource that allows Web clients to fetch HTTP-based resources over HTTPX.
 /// </summary>
 /// <param name="ResourceName">Resource name of proxy resource.</param>
 /// <param name="DefaultXmppClient">Default XMPP client.</param>
 /// <param name="MaxChunkSize">Max Chunk Size to use.</param>
 public HttpxProxy(string ResourceName, XmppClient DefaultXmppClient, int MaxChunkSize)
     : this(ResourceName, DefaultXmppClient, MaxChunkSize, null, null)
 {
 }
 /// <summary>
 /// Implements an XMPP sensor server interface.
 ///
 /// The interface is defined in the IEEE XMPP IoT extensions:
 /// https://gitlab.com/IEEE-SA/XMPPI/IoT
 ///
 /// It also supports the event subscription pattern, documented in the iot-events proto-XEP:
 /// http://www.xmpp.org/extensions/inbox/iot-events.html
 /// </summary>
 /// <param name="Client">XMPP Client</param>
 /// <param name="SupportsEvents">If events are supported.</param>
 public SensorServer(XmppClient Client, bool SupportsEvents)
     : this(Client, null, SupportsEvents)
 {
 }
Exemple #27
0
        private SensorDataClientRequest DoReadout(Waher.Things.SensorData.FieldType Types)
        {
            XmppClient Client = this.XmppAccountNode.Client;
            string     Id     = Guid.NewGuid().ToString();

            RosterItem Item = Client[this.BareJID];
            string     Jid  = Item.LastPresenceFullJid;

            CustomSensorDataClientRequest Request = new CustomSensorDataClientRequest(Id, string.Empty, string.Empty, null,
                                                                                      Types, null, DateTime.MinValue, DateTime.MaxValue, DateTime.Now, string.Empty, string.Empty, string.Empty);

            Request.Accept(false);
            Request.Started();

            Client.SendServiceDiscoveryRequest(Jid, (sender, e) =>
            {
                if (e.Ok)
                {
                    List <Waher.Things.SensorData.Field> Fields = new List <Waher.Things.SensorData.Field>();
                    DateTime Now = DateTime.Now;

                    foreach (KeyValuePair <string, bool> Feature in e.Features)
                    {
                        Fields.Add(new Waher.Things.SensorData.BooleanField(Waher.Things.ThingReference.Empty, Now,
                                                                            Feature.Key, Feature.Value, Waher.Things.SensorData.FieldType.Momentary, Waher.Things.SensorData.FieldQoS.AutomaticReadout));
                    }

                    bool VersionDone = false;

                    if ((Types & Waher.Things.SensorData.FieldType.Identity) != 0)
                    {
                        foreach (Identity Identity in e.Identities)
                        {
                            Fields.Add(new Waher.Things.SensorData.StringField(Waher.Things.ThingReference.Empty, Now,
                                                                               Identity.Type, Identity.Category + (string.IsNullOrEmpty(Identity.Name) ? string.Empty : " (" + Identity.Name + ")"),
                                                                               Waher.Things.SensorData.FieldType.Identity,
                                                                               Waher.Things.SensorData.FieldQoS.AutomaticReadout));
                        }

                        if (e.HasFeature(XmppClient.NamespaceSoftwareVersion))
                        {
                            Client.SendSoftwareVersionRequest(Jid, (sender2, e2) =>
                            {
                                Now = DateTime.Now;

                                if (e2.Ok)
                                {
                                    Request.LogFields(new Waher.Things.SensorData.Field[]
                                    {
                                        new Waher.Things.SensorData.StringField(Waher.Things.ThingReference.Empty, Now, "Client, Name", e2.Name,
                                                                                Waher.Things.SensorData.FieldType.Identity, Waher.Things.SensorData.FieldQoS.AutomaticReadout),
                                        new Waher.Things.SensorData.StringField(Waher.Things.ThingReference.Empty, Now, "Client, OS", e2.OS,
                                                                                Waher.Things.SensorData.FieldType.Identity, Waher.Things.SensorData.FieldQoS.AutomaticReadout),
                                        new Waher.Things.SensorData.StringField(Waher.Things.ThingReference.Empty, Now, "Client, Version", e2.Version,
                                                                                Waher.Things.SensorData.FieldType.Identity, Waher.Things.SensorData.FieldQoS.AutomaticReadout),
                                    });
                                }
                                else
                                {
                                    Request.LogErrors(new Waher.Things.ThingError[]
                                    {
                                        new Waher.Things.ThingError(Waher.Things.ThingReference.Empty, Now, "Unable to read software version.")
                                    });
                                }

                                VersionDone = true;

                                if (VersionDone)
                                {
                                    Request.Done();
                                }
                            }, null);
                        }
                        else
                        {
                            VersionDone = true;
                        }
                    }
                    else
                    {
                        VersionDone = true;
                    }

                    Request.LogFields(Fields);

                    if (VersionDone)
                    {
                        Request.Done();
                    }
                }
                else
                {
                    Request.Fail("Unable to perform a service discovery.");
                }
            }, null);

            return(Request);
        }
Exemple #28
0
 public XmppOther(TreeNode Parent, XmppClient Client, string BareJid)
     : base(Parent, Client, BareJid)
 {
 }
Exemple #29
0
 public void Login(string Username, string Password)
 {
     client = new XmppClient(Server, Username, Password);
 }
Exemple #30
0
        static void Main(string[] _)
        {
            try
            {
                Console.ForegroundColor = ConsoleColor.White;

                Console.Out.WriteLine("Welcome to the Mock Temperature sensor application.");
                Console.Out.WriteLine(new string('-', 79));
                Console.Out.WriteLine("This application will simulate an outside temperature sensor.");
                Console.Out.WriteLine("Values will be published over XMPP using the interface defined in the IEEE XMPP IoT extensions.");
                Console.Out.WriteLine("You can also chat with the sensor.");

                Log.Register(new ConsoleEventSink());
                Log.RegisterExceptionToUnnest(typeof(System.Runtime.InteropServices.ExternalException));
                Log.RegisterExceptionToUnnest(typeof(System.Security.Authentication.AuthenticationException));

                credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config",
                                                                                        Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name.
                                                                                        Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password.
                                                                                        typeof(Program).Assembly);

                using (XmppClient Client = new XmppClient(credentials, "en", typeof(Program).Assembly))
                {
                    if (credentials.Sniffer)
                    {
                        Client.Add(new ConsoleOutSniffer(BinaryPresentationMethod.ByteCount, LineEnding.PadWithSpaces));
                    }

                    if (!string.IsNullOrEmpty(credentials.Events))
                    {
                        Log.Register(new XmppEventSink("XMPP Event Sink", Client, credentials.Events, false));
                    }

                    if (!string.IsNullOrEmpty(credentials.ThingRegistry))
                    {
                        thingRegistryClient = new ThingRegistryClient(Client, credentials.ThingRegistry);

                        thingRegistryClient.Claimed += (sender, e) =>
                        {
                            ownerJid = e.JID;
                            Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic));
                            return(Task.CompletedTask);
                        };

                        thingRegistryClient.Disowned += (sender, e) =>
                        {
                            Log.Informational("Thing has been disowned.", ownerJid);
                            ownerJid = string.Empty;
                            Register();
                            return(Task.CompletedTask);
                        };

                        thingRegistryClient.Removed += (sender, e) =>
                        {
                            Log.Informational("Thing has been removed from the public registry.", ownerJid);
                            return(Task.CompletedTask);
                        };
                    }

                    ProvisioningClient ProvisioningClient = null;
                    if (!string.IsNullOrEmpty(credentials.Provisioning))
                    {
                        ProvisioningClient = new ProvisioningClient(Client, credentials.Provisioning);
                    }

                    Timer ConnectionTimer = new Timer((P) =>
                    {
                        if (Client.State == XmppState.Offline || Client.State == XmppState.Error || Client.State == XmppState.Authenticating)
                        {
                            try
                            {
                                Client.Reconnect();
                            }
                            catch (Exception ex)
                            {
                                Log.Critical(ex);
                            }
                        }
                    }, null, 60000, 60000);

                    bool Connected = false;
                    bool ImmediateReconnect;

                    Client.OnStateChanged += (sender, NewState) =>
                    {
                        switch (NewState)
                        {
                        case XmppState.Connected:
                            Connected = true;

                            if (!registered && thingRegistryClient != null)
                            {
                                Register();
                            }
                            break;

                        case XmppState.Offline:
                            ImmediateReconnect = Connected;
                            Connected          = false;

                            if (ImmediateReconnect)
                            {
                                Client.Reconnect();
                            }
                            break;
                        }

                        return(Task.CompletedTask);
                    };

                    Client.OnPresenceSubscribe += (sender, e) =>
                    {
                        e.Accept();                             // TODO: Provisioning

                        RosterItem Item = Client.GetRosterItem(e.FromBareJID);
                        if (Item is null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From)
                        {
                            Client.RequestPresenceSubscription(e.FromBareJID);
                        }

                        Client.SetPresence(Availability.Chat);

                        return(Task.CompletedTask);
                    };

                    Client.OnPresenceUnsubscribe += (sender, e) =>
                    {
                        e.Accept();
                        return(Task.CompletedTask);
                    };

                    Client.OnRosterItemUpdated += (sender, e) =>
                    {
                        if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe)
                        {
                            Client.RemoveRosterItem(e.BareJid);
                        }

                        return(Task.CompletedTask);
                    };

                    bool SwitchOn = false;

                    SensorServer SensorServer = new SensorServer(Client, ProvisioningClient, false);
                    SensorServer.OnExecuteReadoutRequest += (Sender, Request) =>
                    {
                        DateTime Now = DateTime.Now;

                        Log.Informational("Readout requested", string.Empty, Request.Actor);

                        Request.ReportFields(true, new BooleanField(ThingReference.Empty, Now, "Lamp", SwitchOn, FieldType.Momentary, FieldQoS.AutomaticReadout));

                        return(Task.CompletedTask);
                    };

                    ControlServer ControlServer = new ControlServer(Client,
                                                                    new BooleanControlParameter("Lamp", "Control", "Lamp switch on.", "If checked, lamp is turned on.",
                                                                                                (Node) => Task.FromResult <bool?>(SwitchOn),
                                                                                                (Node, Value) =>
                    {
                        SwitchOn = Value;
                        Log.Informational(Environment.NewLine + Environment.NewLine + "Lamp turned " + (SwitchOn ? "ON" : "OFF") + Environment.NewLine + Environment.NewLine);
                        return(Task.CompletedTask);
                    }));

                    BobClient  BobClient  = new BobClient(Client, Path.Combine(Path.GetTempPath(), "BitsOfBinary"));
                    ChatServer ChatServer = new ChatServer(Client, BobClient, SensorServer, ControlServer, ProvisioningClient);

                    InteroperabilityServer InteroperabilityServer = new InteroperabilityServer(Client);
                    InteroperabilityServer.OnGetInterfaces += (sender, e) =>
                    {
                        e.Add("XMPP.IoT.Actuator.Lamp");
                        return(Task.CompletedTask);
                    };

                    Client.Connect();

                    while (true)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Out.WriteLine(ex.Message);
            }
            finally
            {
                Log.Terminate();
            }
        }
 /// <summary>
 /// Implements an XMPP control server interface.
 ///
 /// The interface is defined in the IEEE XMPP IoT extensions:
 /// https://gitlab.com/IEEE-SA/XMPPI/IoT
 /// </summary>
 /// <param name="Client">XMPP Client</param>
 /// <param name="Parameters">Default set of control parameters. If set of control parameters vary depending on node, leave this
 /// field blank, and provide an event handler for the <see cref="OnGetControlParameters"/> event.</param>
 public ControlServer(XmppClient Client, params ControlParameter[] Parameters)
     : this(Client, null, Parameters)
 {
 }
Exemple #32
0
 /// <summary>
 /// Class managing a SOCKS5 proxy associated with the current XMPP server.
 /// </summary>
 /// <param name="Client">XMPP Client.</param>
 public Socks5Proxy(XmppClient Client)
     : this(Client, null)
 {
 }
Exemple #33
0
 public XmppSensor(TreeNode Parent, XmppClient Client, string BareJid, bool SupportsEventSubscripton)
     : base(Parent, Client, BareJid)
 {
     this.suportsEvents = SupportsEventSubscripton;
 }
Exemple #34
0
        private async void StartSensor()
        {
            try
            {
                Log.Informational("Starting application.");

                SimpleXmppConfiguration xmppConfiguration = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config",
                                                                                                                      Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name.
                                                                                                                      Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password.
                                                                                                                      FormSignatureKey, FormSignatureSecret, typeof(App).GetTypeInfo().Assembly);

                Log.Informational("Connecting to XMPP server.");

                xmppClient = xmppConfiguration.GetClient("en", typeof(App).GetTypeInfo().Assembly, false);
                xmppClient.AllowRegistration(FormSignatureKey, FormSignatureSecret);

                if (xmppConfiguration.Sniffer && MainPage.Sniffer != null)
                {
                    xmppClient.Add(MainPage.Sniffer);
                }

                if (!string.IsNullOrEmpty(xmppConfiguration.Events))
                {
                    Log.Register(new XmppEventSink("XMPP Event Sink", xmppClient, xmppConfiguration.Events, false));
                }

                if (!string.IsNullOrEmpty(xmppConfiguration.ThingRegistry))
                {
                    thingRegistryClient = new ThingRegistryClient(xmppClient, xmppConfiguration.ThingRegistry);

                    thingRegistryClient.Claimed += (sender, e) =>
                    {
                        ownerJid = e.JID;
                        Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic));
                        this.RaiseOwnershipChanged();
                    };

                    thingRegistryClient.Disowned += (sender, e) =>
                    {
                        Log.Informational("Thing has been disowned.", ownerJid);
                        ownerJid = string.Empty;
                        this.Register();                            // Will call this.OwnershipChanged() after successful registration.
                    };

                    thingRegistryClient.Removed += (sender, e) =>
                    {
                        Log.Informational("Thing has been removed from the public registry.", ownerJid);
                    };
                }

                if (!string.IsNullOrEmpty(xmppConfiguration.Provisioning))
                {
                    provisioningClient = new ProvisioningClient(xmppClient, xmppConfiguration.Provisioning);
                }

                Timer ConnectionTimer = new Timer((P) =>
                {
                    if (xmppClient.State == XmppState.Offline || xmppClient.State == XmppState.Error || xmppClient.State == XmppState.Authenticating)
                    {
                        try
                        {
                            Log.Informational("Reconnecting.");
                            xmppClient.Reconnect();
                        }
                        catch (Exception ex)
                        {
                            Log.Critical(ex);
                        }
                    }
                }, null, 60000, 60000);

                xmppClient.OnStateChanged += (sender, NewState) =>
                {
                    Log.Informational(NewState.ToString());

                    switch (NewState)
                    {
                    case XmppState.Connected:
                        connected = true;

                        if (!registered && thingRegistryClient != null)
                        {
                            this.Register();
                        }
                        break;

                    case XmppState.Offline:
                        immediateReconnect = connected;
                        connected          = false;

                        if (immediateReconnect)
                        {
                            xmppClient.Reconnect();
                        }
                        break;
                    }
                };

                xmppClient.OnPresenceSubscribe += (sender, e) =>
                {
                    Log.Informational("Subscription request received from " + e.From + ".");

                    e.Accept();                         // TODO: Provisioning

                    RosterItem Item = xmppClient.GetRosterItem(e.FromBareJID);
                    if (Item == null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From)
                    {
                        xmppClient.RequestPresenceSubscription(e.FromBareJID);
                    }

                    xmppClient.SetPresence(Availability.Chat);
                };

                xmppClient.OnPresenceUnsubscribe += (sender, e) =>
                {
                    Log.Informational("Unsubscription request received from " + e.From + ".");
                    e.Accept();
                };

                xmppClient.OnRosterItemUpdated += (sender, e) =>
                {
                    if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe)
                    {
                        xmppClient.RemoveRosterItem(e.BareJid);
                    }
                };

                LinkedList <DayHistoryRecord>    DayHistoricalValues    = new LinkedList <DayHistoryRecord>();
                LinkedList <MinuteHistoryRecord> MinuteHistoricalValues = new LinkedList <MinuteHistoryRecord>();
                DateTime SampleTime  = DateTime.Now;
                DateTime PeriodStart = SampleTime.Date;
                DateTime Now;
                DateTime MinTime            = SampleTime;
                DateTime MaxTime            = SampleTime;
                double   CurrentTemperature = this.ReadTemp();
                double   MinTemp            = CurrentTemperature;
                double   MaxTemp            = CurrentTemperature;
                double   SumTemp            = CurrentTemperature;
                int      NrTemp             = 1;
                int      NrDayRecords       = 0;
                int      NrMinuteRecords    = 0;
                object   SampleSynch        = new object();

                this.sampleTimer = new Timer((P) =>
                {
                    lock (SampleSynch)
                    {
                        Now = DateTime.Now;

                        if (Now.Date != PeriodStart.Date)
                        {
                            DayHistoryRecord Rec = new DayHistoryRecord(PeriodStart.Date, PeriodStart.Date.AddDays(1).AddMilliseconds(-1),
                                                                        MinTemp, MaxTemp, SumTemp / NrTemp);

                            DayHistoricalValues.AddFirst(Rec);

                            if (NrDayRecords < MaxRecordsPerPeriod)
                            {
                                NrDayRecords++;
                            }
                            else
                            {
                                DayHistoricalValues.RemoveLast();
                            }

                            // TODO: Persistence

                            PeriodStart = Now.Date;
                            SumTemp     = 0;
                            NrTemp      = 0;
                        }

                        CurrentTemperature = this.ReadTemp();

                        if (Now.Minute != SampleTime.Minute)
                        {
                            MinuteHistoryRecord Rec = new MinuteHistoryRecord(Now, CurrentTemperature);

                            MinuteHistoricalValues.AddFirst(Rec);

                            if (NrMinuteRecords < MaxRecordsPerPeriod)
                            {
                                NrMinuteRecords++;
                            }
                            else
                            {
                                MinuteHistoricalValues.RemoveLast();
                            }

                            // TODO: Persistence
                        }

                        SampleTime = Now;

                        if (CurrentTemperature < MinTemp)
                        {
                            MinTemp = CurrentTemperature;
                            MinTime = SampleTime;
                        }

                        if (CurrentTemperature > MaxTemp)
                        {
                            MaxTemp = CurrentTemperature;
                            MaxTime = SampleTime;
                        }

                        SumTemp += CurrentTemperature;
                        NrTemp++;
                    }

                    if (this.sensorServer.HasSubscriptions(ThingReference.Empty))
                    {
                        this.sensorServer.NewMomentaryValues(new QuantityField(ThingReference.Empty, SampleTime, "Temperature",
                                                                               CurrentTemperature, 1, "°C", FieldType.Momentary, FieldQoS.AutomaticReadout));
                    }

                    this.UpdateMainWindow(CurrentTemperature, MinTemp, MaxTemp, SumTemp / NrTemp);
                }, null, 1000 - PeriodStart.Millisecond, 1000);

                this.sensorServer = new SensorServer(xmppClient, provisioningClient, true);
                this.sensorServer.OnExecuteReadoutRequest += (Sender, Request) =>
                {
                    Log.Informational("Readout requested by " + Request.From, string.Empty, Request.Actor);

                    List <Field> Fields          = new List <Field>();
                    bool         IncludeTemp     = Request.IsIncluded("Temperature");
                    bool         IncludeTempMin  = Request.IsIncluded("Temperature, Min");
                    bool         IncludeTempMax  = Request.IsIncluded("Temperature, Max");
                    bool         IncludeTempAvg  = Request.IsIncluded("Temperature, Average");
                    bool         IncludePeak     = Request.IsIncluded(FieldType.Peak);
                    bool         IncludeComputed = Request.IsIncluded(FieldType.Computed);

                    lock (SampleSynch)
                    {
                        if (IncludeTemp && Request.IsIncluded(FieldType.Momentary))
                        {
                            Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature", CurrentTemperature, 1, "°C",
                                                         FieldType.Momentary, FieldQoS.AutomaticReadout));
                        }

                        if (IncludePeak)
                        {
                            if (IncludeTempMin)
                            {
                                Fields.Add(new QuantityField(ThingReference.Empty, MinTime, "Temperature, Min", MinTemp, 1, "°C",
                                                             FieldType.Peak, FieldQoS.AutomaticReadout));
                            }

                            if (IncludeTempMax)
                            {
                                Fields.Add(new QuantityField(ThingReference.Empty, MaxTime, "Temperature, Max", MaxTemp, 1, "°C",
                                                             FieldType.Peak, FieldQoS.AutomaticReadout));
                            }
                        }

                        if (IncludeTempAvg && IncludeComputed)
                        {
                            Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature, Average", SumTemp / NrTemp, 2, "°C",
                                                         FieldType.Computed, FieldQoS.AutomaticReadout));
                        }

                        if (Request.IsIncluded(FieldType.Historical))
                        {
                            foreach (DayHistoryRecord Rec in DayHistoricalValues)
                            {
                                if (!Request.IsIncluded(Rec.PeriodStart))
                                {
                                    continue;
                                }

                                if (Fields.Count >= 100)
                                {
                                    Request.ReportFields(false, Fields);
                                    Fields.Clear();
                                }

                                if (IncludePeak)
                                {
                                    if (IncludeTempMin)
                                    {
                                        Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Min", Rec.MinTemperature, 1, "°C",
                                                                     FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout));
                                    }

                                    if (IncludeTempMax)
                                    {
                                        Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Max", Rec.MaxTemperature, 1, "°C",
                                                                     FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout));
                                    }
                                }

                                if (IncludeTempAvg && IncludeComputed)
                                {
                                    Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Average", Rec.AverageTemperature, 1, "°C",
                                                                 FieldType.Computed | FieldType.Historical, FieldQoS.AutomaticReadout));
                                }
                            }

                            foreach (MinuteHistoryRecord Rec in MinuteHistoricalValues)
                            {
                                if (!Request.IsIncluded(Rec.Timestamp))
                                {
                                    continue;
                                }

                                if (IncludeTemp)
                                {
                                    if (Fields.Count >= 100)
                                    {
                                        Request.ReportFields(false, Fields);
                                        Fields.Clear();
                                    }

                                    Fields.Add(new QuantityField(ThingReference.Empty, Rec.Timestamp, "Temperature", Rec.Temperature, 1, "°C",
                                                                 FieldType.Historical, FieldQoS.AutomaticReadout));
                                }
                            }
                        }
                    }

                    Request.ReportFields(true, Fields);
                };

                this.bobClient  = new BobClient(this.xmppClient, Path.Combine(Path.GetTempPath(), "BitsOfBinary"));
                this.chatServer = new ChatServer(this.xmppClient, this.bobClient, this.sensorServer);

                this.interoperabilityServer = new InteroperabilityServer(xmppClient);
                this.interoperabilityServer.OnGetInterfaces += (sender, e) =>
                {
                    e.Add("XMPP.IoT.Sensor.Temperature",
                          "XMPP.IoT.Sensor.Temperature.History",
                          "XMPP.IoT.Sensor.Temperature.Average",
                          "XMPP.IoT.Sensor.Temperature.Average.History",
                          "XMPP.IoT.Sensor.Temperature.Min",
                          "XMPP.IoT.Sensor.Temperature.Min.History",
                          "XMPP.IoT.Sensor.Temperature.Max",
                          "XMPP.IoT.Sensor.Temperature.Max.History");
                };

                xmppClient.Connect();
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await Dialog.ShowAsync();
            }
        }
Exemple #35
0
        private void MyLegalIdentities_Click(object sender, RoutedEventArgs e)
        {
            this.contractsClient.GetLegalIdentities((sender2, e2) =>
            {
                if (e2.Ok)
                {
                    if (e2.Identities is null || e2.Identities.Length == 0)
                    {
                        MainWindow.MessageBox("No legal identities are regitered.", "Identities", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        foreach (LegalIdentity Identity in e2.Identities)
                        {
                            StringBuilder Markdown = new StringBuilder();

                            Output(XmppClient.GetBareJID(e2.To), Markdown, Identity.GetTags());

                            MainWindow.currentInstance.Dispatcher.BeginInvoke(new ThreadStart(() =>
                            {
                                MainWindow.currentInstance.ChatMessage(XmppClient.GetBareJID(e2.From), XmppClient.GetBareJID(e2.To),
                                                                       Markdown.ToString(), true);
                            }));
                        }
                    }
                }
Exemple #36
0
 /// <summary>
 /// Client managing the Personal Eventing Protocol (XEP-0163).
 /// https://xmpp.org/extensions/xep-0163.html
 /// </summary>
 /// <param name="Client">XMPP Client to use.</param>
 public PepClient(XmppClient Client)
     : this(Client, string.Empty)
 {
 }
Exemple #37
0
        public static void Main(string[] _)
        {
            try
            {
                Console.ForegroundColor = ConsoleColor.White;

                Console.Out.WriteLine("Welcome to the Mock Temperature sensor application.");
                Console.Out.WriteLine(new string('-', 79));
                Console.Out.WriteLine("This application will simulate an outside temperature sensor.");
                Console.Out.WriteLine("Values will be published over XMPP using the interface defined in the IEEE XMPP IoT extensions.");
                Console.Out.WriteLine("You can also chat with the sensor.");

                Log.Register(new ConsoleEventSink());
                Log.RegisterExceptionToUnnest(typeof(System.Runtime.InteropServices.ExternalException));
                Log.RegisterExceptionToUnnest(typeof(System.Security.Authentication.AuthenticationException));

                credentials = SimpleXmppConfiguration.GetConfigUsingSimpleConsoleDialog("xmpp.config",
                                                                                        Guid.NewGuid().ToString().Replace("-", string.Empty), // Default user name.
                                                                                        Guid.NewGuid().ToString().Replace("-", string.Empty), // Default password.
                                                                                        typeof(Program).Assembly);

                using (XmppClient Client = new XmppClient(credentials, "en", typeof(Program).Assembly))
                {
                    if (credentials.Sniffer)
                    {
                        Client.Add(new ConsoleOutSniffer(BinaryPresentationMethod.ByteCount, LineEnding.PadWithSpaces));
                    }

                    if (!string.IsNullOrEmpty(credentials.Events))
                    {
                        Log.Register(new XmppEventSink("XMPP Event Sink", Client, credentials.Events, false));
                    }

                    if (!string.IsNullOrEmpty(credentials.ThingRegistry))
                    {
                        thingRegistryClient = new ThingRegistryClient(Client, credentials.ThingRegistry);

                        thingRegistryClient.Claimed += (sender, e) =>
                        {
                            ownerJid = e.JID;
                            Log.Informational("Thing has been claimed.", ownerJid, new KeyValuePair <string, object>("Public", e.IsPublic));
                            return(Task.CompletedTask);
                        };

                        thingRegistryClient.Disowned += (sender, e) =>
                        {
                            Log.Informational("Thing has been disowned.", ownerJid);
                            ownerJid = string.Empty;
                            Register();
                            return(Task.CompletedTask);
                        };

                        thingRegistryClient.Removed += (sender, e) =>
                        {
                            Log.Informational("Thing has been removed from the public registry.", ownerJid);
                            return(Task.CompletedTask);
                        };
                    }

                    ProvisioningClient ProvisioningClient = null;
                    if (!string.IsNullOrEmpty(credentials.Provisioning))
                    {
                        ProvisioningClient = new ProvisioningClient(Client, credentials.Provisioning);
                    }

                    Timer ConnectionTimer = new Timer((P) =>
                    {
                        if (Client.State == XmppState.Offline || Client.State == XmppState.Error || Client.State == XmppState.Authenticating)
                        {
                            try
                            {
                                Client.Reconnect();
                            }
                            catch (Exception ex)
                            {
                                Log.Critical(ex);
                            }
                        }
                    }, null, 60000, 60000);

                    bool Connected = false;
                    bool ImmediateReconnect;

                    Client.OnStateChanged += (sender, NewState) =>
                    {
                        switch (NewState)
                        {
                        case XmppState.Connected:
                            Connected = true;

                            if (!registered && thingRegistryClient != null)
                            {
                                Register();
                            }
                            break;

                        case XmppState.Offline:
                            ImmediateReconnect = Connected;
                            Connected          = false;

                            if (ImmediateReconnect)
                            {
                                Client.Reconnect();
                            }
                            break;
                        }

                        return(Task.CompletedTask);
                    };

                    Client.OnPresenceSubscribe += (sender, e) =>
                    {
                        e.Accept();                             // TODO: Provisioning

                        RosterItem Item = Client.GetRosterItem(e.FromBareJID);
                        if (Item is null || Item.State == SubscriptionState.None || Item.State == SubscriptionState.From)
                        {
                            Client.RequestPresenceSubscription(e.FromBareJID);
                        }

                        Client.SetPresence(Availability.Chat);

                        return(Task.CompletedTask);
                    };

                    Client.OnPresenceUnsubscribe += (sender, e) =>
                    {
                        e.Accept();
                        return(Task.CompletedTask);
                    };

                    Client.OnRosterItemUpdated += (sender, e) =>
                    {
                        if (e.State == SubscriptionState.None && e.PendingSubscription != PendingSubscription.Subscribe)
                        {
                            Client.RemoveRosterItem(e.BareJid);
                        }

                        return(Task.CompletedTask);
                    };

                    LinkedList <DayHistoryRecord>    DayHistoricalValues    = new LinkedList <DayHistoryRecord>();
                    LinkedList <MinuteHistoryRecord> MinuteHistoricalValues = new LinkedList <MinuteHistoryRecord>();
                    DateTime SampleTime  = DateTime.Now;
                    DateTime PeriodStart = SampleTime.Date;
                    DateTime Now;
                    DateTime MinTime            = SampleTime;
                    DateTime MaxTime            = SampleTime;
                    double   CurrentTemperature = ReadTemp();
                    double   MinTemp            = CurrentTemperature;
                    double   MaxTemp            = CurrentTemperature;
                    double   SumTemp            = CurrentTemperature;
                    int      NrTemp             = 1;
                    int      NrDayRecords       = 0;
                    int      NrMinuteRecords    = 0;
                    object   SampleSynch        = new object();

                    SensorServer SensorServer = new SensorServer(Client, ProvisioningClient, true);
                    SensorServer.OnExecuteReadoutRequest += (Sender, Request) =>
                    {
                        Log.Informational("Readout requested", string.Empty, Request.Actor);

                        List <Field> Fields          = new List <Field>();
                        bool         IncludeTemp     = Request.IsIncluded("Temperature");
                        bool         IncludeTempMin  = Request.IsIncluded("Temperature, Min");
                        bool         IncludeTempMax  = Request.IsIncluded("Temperature, Max");
                        bool         IncludeTempAvg  = Request.IsIncluded("Temperature, Average");
                        bool         IncludePeak     = Request.IsIncluded(FieldType.Peak);
                        bool         IncludeComputed = Request.IsIncluded(FieldType.Computed);

                        lock (SampleSynch)
                        {
                            if (IncludeTemp && Request.IsIncluded(FieldType.Momentary))
                            {
                                Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature", CurrentTemperature, 1, "°C",
                                                             FieldType.Momentary, FieldQoS.AutomaticReadout));
                            }

                            if (IncludePeak)
                            {
                                if (IncludeTempMin)
                                {
                                    Fields.Add(new QuantityField(ThingReference.Empty, MinTime, "Temperature, Min", MinTemp, 1, "°C",
                                                                 FieldType.Peak, FieldQoS.AutomaticReadout));
                                }

                                if (IncludeTempMax)
                                {
                                    Fields.Add(new QuantityField(ThingReference.Empty, MaxTime, "Temperature, Max", MaxTemp, 1, "°C",
                                                                 FieldType.Peak, FieldQoS.AutomaticReadout));
                                }
                            }

                            if (IncludeTempAvg && IncludeComputed)
                            {
                                Fields.Add(new QuantityField(ThingReference.Empty, SampleTime, "Temperature, Average", SumTemp / NrTemp, 2, "°C",
                                                             FieldType.Computed, FieldQoS.AutomaticReadout));
                            }

                            if (Request.IsIncluded(FieldType.Historical))
                            {
                                foreach (DayHistoryRecord Rec in DayHistoricalValues)
                                {
                                    if (!Request.IsIncluded(Rec.PeriodStart))
                                    {
                                        continue;
                                    }

                                    if (Fields.Count >= 100)
                                    {
                                        Request.ReportFields(false, Fields);
                                        Fields.Clear();
                                    }

                                    if (IncludePeak)
                                    {
                                        if (IncludeTempMin)
                                        {
                                            Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Min", Rec.MinTemperature, 1, "°C",
                                                                         FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout));
                                        }

                                        if (IncludeTempMax)
                                        {
                                            Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Max", Rec.MaxTemperature, 1, "°C",
                                                                         FieldType.Peak | FieldType.Historical, FieldQoS.AutomaticReadout));
                                        }
                                    }

                                    if (IncludeTempAvg && IncludeComputed)
                                    {
                                        Fields.Add(new QuantityField(ThingReference.Empty, Rec.PeriodStart, "Temperature, Average", Rec.AverageTemperature, 1, "°C",
                                                                     FieldType.Computed | FieldType.Historical, FieldQoS.AutomaticReadout));
                                    }
                                }

                                foreach (MinuteHistoryRecord Rec in MinuteHistoricalValues)
                                {
                                    if (!Request.IsIncluded(Rec.Timestamp))
                                    {
                                        continue;
                                    }

                                    if (IncludeTemp)
                                    {
                                        if (Fields.Count >= 100)
                                        {
                                            Request.ReportFields(false, Fields);
                                            Fields.Clear();
                                        }

                                        Fields.Add(new QuantityField(ThingReference.Empty, Rec.Timestamp, "Temperature", Rec.Temperature, 1, "°C",
                                                                     FieldType.Historical, FieldQoS.AutomaticReadout));
                                    }
                                }
                            }
                        }

                        Request.ReportFields(true, Fields);

                        return(Task.CompletedTask);
                    };

                    Timer SampleTimer = new Timer((P) =>
                    {
                        lock (SampleSynch)
                        {
                            Now = DateTime.Now;

                            if (Now.Date != PeriodStart.Date)
                            {
                                DayHistoryRecord Rec = new DayHistoryRecord(PeriodStart.Date, PeriodStart.Date.AddDays(1).AddMilliseconds(-1),
                                                                            MinTemp, MaxTemp, SumTemp / NrTemp);

                                DayHistoricalValues.AddFirst(Rec);

                                if (NrDayRecords < MaxRecordsPerPeriod)
                                {
                                    NrDayRecords++;
                                }
                                else
                                {
                                    DayHistoricalValues.RemoveLast();
                                }

                                // TODO: Persistence

                                PeriodStart = Now.Date;
                                SumTemp     = 0;
                                NrTemp      = 0;
                            }

                            CurrentTemperature = ReadTemp();

                            if (Now.Minute != SampleTime.Minute)
                            {
                                MinuteHistoryRecord Rec = new MinuteHistoryRecord(Now, CurrentTemperature);

                                MinuteHistoricalValues.AddFirst(Rec);

                                if (NrMinuteRecords < MaxRecordsPerPeriod)
                                {
                                    NrMinuteRecords++;
                                }
                                else
                                {
                                    MinuteHistoricalValues.RemoveLast();
                                }

                                // TODO: Persistence
                            }

                            SampleTime = Now;

                            if (CurrentTemperature < MinTemp)
                            {
                                MinTemp = CurrentTemperature;
                                MinTime = SampleTime;
                            }

                            if (CurrentTemperature > MaxTemp)
                            {
                                MaxTemp = CurrentTemperature;
                                MaxTime = SampleTime;
                            }

                            SumTemp += CurrentTemperature;
                            NrTemp++;
                        }

                        if (SensorServer.HasSubscriptions(ThingReference.Empty))
                        {
                            SensorServer.NewMomentaryValues(new QuantityField(ThingReference.Empty, SampleTime, "Temperature",
                                                                              CurrentTemperature, 1, "°C", FieldType.Momentary, FieldQoS.AutomaticReadout));
                        }
                    }, null, 1000 - PeriodStart.Millisecond, 1000);

                    BobClient  BobClient  = new BobClient(Client, Path.Combine(Path.GetTempPath(), "BitsOfBinary"));
                    ChatServer ChatServer = new ChatServer(Client, BobClient, SensorServer, ProvisioningClient);

                    InteroperabilityServer InteroperabilityServer = new InteroperabilityServer(Client);
                    InteroperabilityServer.OnGetInterfaces += (sender, e) =>
                    {
                        e.Add("XMPP.IoT.Sensor.Temperature",
                              "XMPP.IoT.Sensor.Temperature.History",
                              "XMPP.IoT.Sensor.Temperature.Average",
                              "XMPP.IoT.Sensor.Temperature.Average.History",
                              "XMPP.IoT.Sensor.Temperature.Min",
                              "XMPP.IoT.Sensor.Temperature.Min.History",
                              "XMPP.IoT.Sensor.Temperature.Max",
                              "XMPP.IoT.Sensor.Temperature.Max.History");

                        return(Task.CompletedTask);
                    };

                    Client.Connect();

                    while (true)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Out.WriteLine(ex.Message);
            }
            finally
            {
                Log.Terminate();
            }
        }
        private async void Client_OnStateChanged(object Sender, XmppState NewState)
        {
            if (!(Sender is XmppClient Client))
            {
                return;
            }

            if (!Client.TryGetTag("TabID", out object Obj) || !(Obj is string TabID))
            {
                return;
            }

            try
            {
                string Msg;

                switch (NewState)
                {
                case XmppState.Authenticating:
                    Client.SetTag("StartedAuthentication", true);
                    Client.SetTag("EncyptionSuccessful", true);
                    if (this.Step == 0)
                    {
                        ClientEvents.PushEvent(new string[] { TabID }, "ConnectionOK0", "Connection established.", false, "User");

                        this.client.Dispose();
                        this.client = null;

                        this.Step    = 1;
                        this.Updated = DateTime.Now;
                        await Database.Update(this);

                        return;
                    }
                    else
                    {
                        Msg = "Authenticating user.";
                    }
                    break;

                case XmppState.Binding:
                    Msg = "Binding to resource.";
                    break;

                case XmppState.Connected:
                    this.bareJid = Client.BareJID;

                    if (this.createAccount && !string.IsNullOrEmpty(this.accountHumanReadableName))
                    {
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Setting vCard.", false, "User");

                        StringBuilder Xml = new StringBuilder();

                        Xml.Append("<vCard xmlns='vcard-temp'>");
                        Xml.Append("<FN>");
                        Xml.Append(XML.Encode(this.accountHumanReadableName));
                        Xml.Append("</FN>");
                        Xml.Append("<JABBERID>");
                        Xml.Append(XML.Encode(this.client.BareJID));
                        Xml.Append("</JABBERID>");
                        Xml.Append("</vCard>");

                        await Client.IqSetAsync(this.client.BareJID, Xml.ToString());
                    }

                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Checking server features.", false, "User");
                    ServiceDiscoveryEventArgs e = await Client.ServiceDiscoveryAsync(null, string.Empty, string.Empty);

                    if (e.Ok)
                    {
                        this.offlineMessages = e.HasFeature("msgoffline");
                        this.blocking        = e.HasFeature(Networking.XMPP.Abuse.AbuseClient.NamespaceBlocking);
                        this.reporting       = e.HasFeature(Networking.XMPP.Abuse.AbuseClient.NamespaceReporting);
                        this.abuse           = e.HasFeature(Networking.XMPP.Abuse.AbuseClient.NamespaceAbuseReason);
                        this.spam            = e.HasFeature(Networking.XMPP.Abuse.AbuseClient.NamespaceSpamReason);
                    }
                    else
                    {
                        this.offlineMessages = false;
                        this.blocking        = false;
                        this.reporting       = false;
                        this.abuse           = false;
                        this.spam            = false;
                    }

                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Checking account features.", false, "User");
                    e = await Client.ServiceDiscoveryAsync(null, Client.BareJID, string.Empty);

                    this.pep = e.Ok && this.ContainsIdentity("pep", "pubsub", e);

                    ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Checking server components.", false, "User");
                    ServiceItemsDiscoveryEventArgs e2 = await Client.ServiceItemsDiscoveryAsync(null, string.Empty, string.Empty);

                    this.thingRegistry = string.Empty;
                    this.provisioning  = string.Empty;
                    this.events        = string.Empty;
                    this.pubSub        = string.Empty;
                    this.legal         = string.Empty;

                    if (e2.Ok)
                    {
                        foreach (Item Item in e2.Items)
                        {
                            ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Checking component features for " + Item.JID, false, "User");

                            e = await Client.ServiceDiscoveryAsync(null, Item.JID, string.Empty);

                            if (e.HasFeature(Networking.XMPP.Provisioning.ThingRegistryClient.NamespaceDiscovery))
                            {
                                this.thingRegistry = Item.JID;
                            }

                            if (e.HasFeature(Networking.XMPP.Provisioning.ProvisioningClient.NamespaceProvisioningDevice))
                            {
                                this.provisioning = Item.JID;
                            }

                            if (e.HasFeature(Networking.XMPP.PubSub.PubSubClient.NamespacePubSub) && this.ContainsIdentity("service", "pubsub", e))
                            {
                                this.pubSub = Item.JID;
                            }

                            if (e.HasFeature(Waher.Events.XMPP.XmppEventSink.NamespaceEventLogging))
                            {
                                this.events = Item.JID;
                            }

                            if (e.HasFeature(Networking.XMPP.Contracts.ContractsClient.NamespaceLegalIdentities))
                            {
                                this.legal = Item.JID;
                            }
                        }
                    }

                    Dictionary <string, object> ConnectionInfo = new Dictionary <string, object>()
                    {
                        { "msg", "Connection successful." },
                        { "offlineMsg", this.offlineMessages },
                        { "blocking", this.blocking },
                        { "reporting", this.reporting },
                        { "abuse", this.abuse },
                        { "spam", this.spam },
                        { "pep", this.pep ? this.bareJid : string.Empty },
                        { "thingRegistry", this.thingRegistry },
                        { "provisioning", this.provisioning },
                        { "eventLog", this.events },
                        { "pubSub", this.pubSub },
                        { "legal", this.legal }
                    };

                    ClientEvents.PushEvent(new string[] { TabID }, "ConnectionOK1", JSON.Encode(ConnectionInfo, false), true, "User");

                    this.client.Dispose();
                    this.client = null;

                    this.Step    = 2;
                    this.Updated = DateTime.Now;
                    await Database.Update(this);

                    return;

                case XmppState.Connecting:
                    Msg = "Connecting to server.";
                    break;

                case XmppState.Error:
                    bool Error = false;
                    Msg = string.Empty;

                    if (this.Step == 0 && this.transportMethod == XmppTransportMethod.C2S)
                    {
                        this.customBinding = true;

                        ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", "Unable to connect properly. Looking for alternative ways to connect.", false, "User");
                        ClientEvents.PushEvent(new string[] { TabID }, "ShowCustomProperties", "{\"visible\":true}", true, "User");

                        using (HttpClient HttpClient = new HttpClient(new HttpClientHandler()
                        {
#if !NETFW
                            ServerCertificateCustomValidationCallback = this.RemoteCertificateValidationCallback,
#endif
                            UseCookies = false
                        })
                        {
                            Timeout = TimeSpan.FromMilliseconds(60000)
                        })
                        {
                            try
                            {
                                HttpResponseMessage Response = await HttpClient.GetAsync("http://" + this.host + "/.well-known/host-meta");

                                Response.EnsureSuccessStatusCode();

                                Stream Stream = await Response.Content.ReadAsStreamAsync();                                         // Regardless of status code, we check for XML content.

                                byte[] Bin = await Response.Content.ReadAsByteArrayAsync();

                                string   CharSet = Response.Content.Headers.ContentType.CharSet;
                                Encoding Encoding;

                                if (string.IsNullOrEmpty(CharSet))
                                {
                                    Encoding = Encoding.UTF8;
                                }
                                else
                                {
                                    Encoding = System.Text.Encoding.GetEncoding(CharSet);
                                }

                                string      XmlResponse = Encoding.GetString(Bin);
                                XmlDocument Doc         = new XmlDocument();
                                Doc.LoadXml(XmlResponse);

                                if (Doc.DocumentElement != null && Doc.DocumentElement.LocalName == "XRD")
                                {
                                    string BoshUrl = null;
                                    string WsUrl   = null;

                                    foreach (XmlNode N in Doc.DocumentElement.ChildNodes)
                                    {
                                        if (N is XmlElement E && E.LocalName == "Link")
                                        {
                                            switch (XML.Attribute(E, "rel"))
                                            {
                                            case "urn:xmpp:alt-connections:xbosh":
                                                BoshUrl = XML.Attribute(E, "href");
                                                break;

                                            case "urn:xmpp:alt-connections:websocket":
                                                WsUrl = XML.Attribute(E, "href");
                                                break;
                                            }
                                        }
                                    }

                                    if (!string.IsNullOrEmpty(WsUrl))
                                    {
                                        this.wsUrl           = WsUrl;
                                        this.transportMethod = XmppTransportMethod.WS;

                                        ClientEvents.PushEvent(new string[] { TabID }, "ShowTransport", "{\"method\":\"WS\"}", true, "User");

                                        this.Connect(TabID);

                                        return;
                                    }
                                    else if (!string.IsNullOrEmpty(BoshUrl))
                                    {
                                        this.boshUrl         = BoshUrl;
                                        this.transportMethod = XmppTransportMethod.BOSH;

                                        ClientEvents.PushEvent(new string[] { TabID }, "ShowTransport", "{\"method\":\"BOSH\"}", true, "User");

                                        this.Connect(TabID);

                                        return;
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                // Ignore.
                            }

                            Msg   = "No alternative binding methods found.";
                            Error = true;
                        }
                    }
                    else
                    {
                        Msg   = "Unable to connect properly.";
                        Error = true;

                        if (Client.TryGetTag("StartedAuthentication", out Obj) && Obj is bool b && b)
                        {
                            if (this.createAccount)
                            {
                                ClientEvents.PushEvent(new string[] { TabID }, "ShowFail2", Msg, false, "User");
                            }
                            else
                            {
                                ClientEvents.PushEvent(new string[] { TabID }, "ShowFail1", Msg, false, "User");
                            }
                            return;
                        }
                    }

                    if (Error)
                    {
                        ClientEvents.PushEvent(new string[] { TabID }, "ConnectionError", Msg, false, "User");

                        this.client.Dispose();
                        this.client = null;

                        return;
                    }
                    break;

                case XmppState.FetchingRoster:
                    Msg = "Fetching roster from server.";
                    break;

                case XmppState.Offline:
                    Msg = "Offline.";
                    break;

                case XmppState.Registering:
                    Msg = "Registering account.";
                    break;

                case XmppState.RequestingSession:
                    Msg = "Requesting session.";
                    break;

                case XmppState.SettingPresence:
                    Msg = "Setting presence.";
                    break;

                case XmppState.StartingEncryption:
                    Msg = "Starting encryption.";
                    Client.SetTag("StartedEncryption", true);
                    break;

                case XmppState.StreamNegotiation:
                    Msg = "Negotiating stream.";
                    break;

                case XmppState.StreamOpened:
                    Msg = "Stream opened.";
                    break;

                default:
                    Msg = NewState.ToString();
                    break;
                }

                ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", Msg, false, "User");
            }
            catch (Exception ex)
            {
                Log.Critical(ex);
                ClientEvents.PushEvent(new string[] { TabID }, "ShowStatus", ex.Message, false, "User");
            }
        }
 public MucManager(XmppClient xmppClient)
 {
     XmppClient = xmppClient;
 }
Exemple #40
0
        /// <summary>
        /// <see cref="AuthenticationMethod.Challenge"/>
        /// </summary>
        public override string Challenge(string Challenge, XmppClient Client)
        {
            byte[] ChallengeBinary = Convert.FromBase64String(Challenge);
            string ChallengeString = System.Text.Encoding.UTF8.GetString(ChallengeBinary);

            foreach (KeyValuePair <string, string> Pair in this.ParseCommaSeparatedParameterList(ChallengeString))
            {
                switch (Pair.Key.ToLower())
                {
                case "r":
                    this.serverNonce = Pair.Value;
                    break;

                case "s":
                    this.saltString = Pair.Value;
                    this.salt       = Convert.FromBase64String(this.saltString);
                    break;

                case "i":
                    this.nrIterations = int.Parse(Pair.Value);
                    break;
                }
            }

            if (string.IsNullOrEmpty(this.serverNonce) || this.salt == null || this.nrIterations <= 0)
            {
                throw new XmppException("Invalid challenge.");
            }

            byte[] SaltedPassword;

            if (string.IsNullOrEmpty(Client.PasswordHash))
            {
                SaltedPassword            = Hi(System.Text.Encoding.UTF8.GetBytes(Client.Password), this.salt, this.nrIterations);          // Client.Pasword.Normalize()	- Normalize method avaialble in .NET 2.0
                Client.PasswordHash       = Convert.ToBase64String(SaltedPassword);
                Client.PasswordHashMethod = "SCRAM-SHA-1";
            }
            else
            {
                SaltedPassword = Convert.FromBase64String(Client.PasswordHash);
            }

            byte[] ClientKey = HMAC(SaltedPassword, System.Text.Encoding.UTF8.GetBytes("Client Key"));
            byte[] StoredKey = H(ClientKey);

            StringBuilder sb;

            sb = new StringBuilder();
            sb.Append("n=");
            sb.Append(Client.UserName);
            sb.Append(",r=");
            sb.Append(this.nonce);
            sb.Append(",r=");
            sb.Append(this.serverNonce);
            sb.Append(",s=");
            sb.Append(this.saltString);
            sb.Append(",i=");
            sb.Append(this.nrIterations.ToString());
            sb.Append(",c=biws,r=");
            sb.Append(this.serverNonce);

            byte[] AuthenticationMessage = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
            byte[] ClientSignature       = HMAC(StoredKey, AuthenticationMessage);
            byte[] ClientProof           = XOR(ClientKey, ClientSignature);

            byte[] ServerKey       = HMAC(SaltedPassword, System.Text.Encoding.UTF8.GetBytes("Server Key"));
            byte[] ServerSignature = HMAC(ServerKey, AuthenticationMessage);

            this.serverSignature = Convert.ToBase64String(ServerSignature);

            sb = new StringBuilder();
            sb.Append("c=biws,r=");                 // biws="n,,"
            sb.Append(this.serverNonce);
            sb.Append(",p=");
            sb.Append(Convert.ToBase64String(ClientProof));

            return(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sb.ToString())));
        }
Exemple #41
0
        private async void Init()
        {
            try
            {
                Log.Informational("Starting application.");

                Types.Initialize(
                    typeof(FilesProvider).GetTypeInfo().Assembly,
                    typeof(RuntimeSettings).GetTypeInfo().Assembly,
                    typeof(IContentEncoder).GetTypeInfo().Assembly,
                    typeof(XmppClient).GetTypeInfo().Assembly,
                    typeof(Waher.Content.Markdown.MarkdownDocument).GetTypeInfo().Assembly,
                    typeof(XML).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Expression).GetTypeInfo().Assembly,
                    typeof(Waher.Script.Graphs.Graph).GetTypeInfo().Assembly,
                    typeof(App).GetTypeInfo().Assembly);

                Database.Register(new FilesProvider(Windows.Storage.ApplicationData.Current.LocalFolder.Path +
                                                    Path.DirectorySeparatorChar + "Data", "Default", 8192, 1000, 8192, Encoding.UTF8, 10000));

#if GPIO
                gpio = GpioController.GetDefault();
                if (gpio != null)
                {
                    if (gpio.TryOpenPin(gpioOutputPin, GpioSharingMode.Exclusive, out this.gpioPin, out GpioOpenStatus Status) &&
                        Status == GpioOpenStatus.PinOpened)
                    {
                        if (this.gpioPin.IsDriveModeSupported(GpioPinDriveMode.Output))
                        {
                            this.gpioPin.SetDriveMode(GpioPinDriveMode.Output);

                            this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                            this.gpioPin.Write(this.output ? GpioPinValue.High : GpioPinValue.Low);

                            await MainPage.Instance.OutputSet(this.output);

                            Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                              new KeyValuePair <string, object>("Output", this.output));
                        }
                        else
                        {
                            Log.Error("Output mode not supported for GPIO pin " + gpioOutputPin.ToString());
                        }
                    }
                    else
                    {
                        Log.Error("Unable to get access to GPIO pin " + gpioOutputPin.ToString());
                    }
                }
#else
                DeviceInformationCollection Devices = await UsbSerial.listAvailableDevicesAsync();

                foreach (DeviceInformation DeviceInfo in Devices)
                {
                    if (DeviceInfo.IsEnabled && DeviceInfo.Name.StartsWith("Arduino"))
                    {
                        Log.Informational("Connecting to " + DeviceInfo.Name);

                        this.arduinoUsb = new UsbSerial(DeviceInfo);
                        this.arduinoUsb.ConnectionEstablished += () =>
                                                                 Log.Informational("USB connection established.");

                        this.arduino              = new RemoteDevice(this.arduinoUsb);
                        this.arduino.DeviceReady += async() =>
                        {
                            try
                            {
                                Log.Informational("Device ready.");

                                this.arduino.pinMode(13, PinMode.OUTPUT);                                    // Onboard LED.
                                this.arduino.digitalWrite(13, PinState.HIGH);

                                this.arduino.pinMode(8, PinMode.INPUT);                                      // PIR sensor (motion detection).

                                this.arduino.pinMode(9, PinMode.OUTPUT);                                     // Relay.

                                this.output = await RuntimeSettings.GetAsync("Actuator.Output", false);

                                this.arduino.digitalWrite(9, this.output.Value ? PinState.HIGH : PinState.LOW);

                                await MainPage.Instance.OutputSet(this.output.Value);

                                Log.Informational("Setting Control Parameter.", string.Empty, "Startup",
                                                  new KeyValuePair <string, object>("Output", this.output));

                                this.arduino.pinMode("A0", PinMode.ANALOG);                                 // Light sensor.
                            }
                            catch (Exception ex)
                            {
                                Log.Critical(ex);
                            }
                        };

                        this.arduinoUsb.ConnectionFailed += message =>
                        {
                            Log.Error("USB connection failed: " + message);
                        };

                        this.arduinoUsb.ConnectionLost += message =>
                        {
                            Log.Error("USB connection lost: " + message);
                        };

                        this.arduinoUsb.begin(57600, SerialConfig.SERIAL_8N1);
                        break;
                    }
                }
#endif
                this.deviceId = await RuntimeSettings.GetAsync("DeviceId", string.Empty);

                if (string.IsNullOrEmpty(this.deviceId))
                {
                    this.deviceId = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    await RuntimeSettings.SetAsync("DeviceId", this.deviceId);
                }

                Log.Informational("Device ID: " + this.deviceId);

                string Host = await RuntimeSettings.GetAsync("XmppHost", "waher.se");

                int Port = (int)await RuntimeSettings.GetAsync("XmppPort", 5222);

                string UserName = await RuntimeSettings.GetAsync("XmppUserName", string.Empty);

                string PasswordHash = await RuntimeSettings.GetAsync("XmppPasswordHash", string.Empty);

                string PasswordHashMethod = await RuntimeSettings.GetAsync("XmppPasswordHashMethod", string.Empty);

                if (string.IsNullOrEmpty(Host) ||
                    Port <= 0 || Port > ushort.MaxValue ||
                    string.IsNullOrEmpty(UserName) ||
                    string.IsNullOrEmpty(PasswordHash) ||
                    string.IsNullOrEmpty(PasswordHashMethod))
                {
                    await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                async() => await this.ShowConnectionDialog(Host, Port, UserName));
                }
                else
                {
                    this.xmppClient = new XmppClient(Host, Port, UserName, PasswordHash, PasswordHashMethod, "en",
                                                     typeof(App).GetTypeInfo().Assembly) // Add "new LogSniffer()" to the end, to output communication to the log.
                    {
                        AllowCramMD5   = false,
                        AllowDigestMD5 = false,
                        AllowPlain     = false,
                        AllowScramSHA1 = true
                    };
                    this.xmppClient.OnStateChanged    += this.StateChanged;
                    this.xmppClient.OnConnectionError += this.ConnectionError;
                    this.AttachFeatures();

                    Log.Informational("Connecting to " + this.xmppClient.Host + ":" + this.xmppClient.Port.ToString());
                    this.xmppClient.Connect();
                }

                this.minuteTimer = new Timer((State) =>
                {
                    if (this.xmppClient != null &&
                        (this.xmppClient.State == XmppState.Error || this.xmppClient.State == XmppState.Offline))
                    {
                        this.xmppClient.Reconnect();
                    }
                }, null, 60000, 60000);
            }
            catch (Exception ex)
            {
                Log.Emergency(ex);

                MessageDialog Dialog = new MessageDialog(ex.Message, "Error");
                await MainPage.Instance.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                            async() => await Dialog.ShowAsync());
            }
        }
Exemple #42
0
 /// <summary>
 /// <see cref="AuthenticationMethod.CheckSuccess"/>
 /// </summary>
 public override bool CheckSuccess(string Success, XmppClient Client)
 {
     return(true);
 }
Exemple #43
0
        //
        // Public Methods
        //
        public SensorClient(string server, string user, string pwd)
        {
            m_user = user;
            m_server = server;
            m_pwd = pwd;
            m_subNH = new List<SubNodeHandler>(3);
            m_bCreated = false;

            m_xmppClient = new XmppClient();
            m_payload = new SensorPayload();
            m_psItem = new Matrix.Xmpp.PubSub.Item();
            m_psJid = new Jid("pubsub." + m_server);
            m_psMgr = new PubSubManager(m_xmppClient);

            _License();
            Connect();
        }
Exemple #44
0
        /// <summary>
        /// <see cref="AuthenticationMethod.Challenge"/>
        /// </summary>
        public override string Challenge(string Challenge, XmppClient Client)
        {
            byte[] ChallengeBinary = Convert.FromBase64String(Challenge);
            string ChallengeString = System.Text.Encoding.UTF8.GetString(ChallengeBinary);

            string Realm = Client.Domain;
            string Nonce = string.Empty;
            string Qop   = string.Empty;

            string[] Qops      = null;
            string   Stale     = string.Empty;
            string   Maxbuf    = string.Empty;
            string   Charset   = string.Empty;
            string   Algorithm = string.Empty;
            string   Cipher    = string.Empty;
            string   Token     = string.Empty;

            byte[] A1;
            string A2;

            if (ChallengeString.StartsWith("rspauth="))
            {
                return(string.Empty);
            }
            else
            {
                foreach (KeyValuePair <string, string> Pair in this.ParseCommaSeparatedParameterList(ChallengeString))
                {
                    switch (Pair.Key.ToLower())
                    {
                    case "realm":
                        Realm = Pair.Value;
                        break;

                    case "nonce":
                        Nonce = Pair.Value;
                        break;

                    case "qop":
                        Qop  = Pair.Value;
                        Qops = Qop.Split(',');
                        break;

                    case "stale":
                        Stale = Pair.Value;
                        break;

                    case "maxbuf":
                        Maxbuf = Pair.Value;
                        break;

                    case "charset":
                        Charset = Pair.Value;
                        break;

                    case "algorithm":
                        Algorithm = Pair.Value;
                        break;

                    case "cipher":
                        Cipher = Pair.Value;
                        break;

                    case "token":
                        Token = Pair.Value;
                        break;
                    }
                }

                bool Auth    = Qops is null ? false : (Array.IndexOf <string>(Qops, "auth") >= 0);
                bool AuthInt = Qops is null ? false : (Array.IndexOf <string>(Qops, "auth-int") >= 0);

                StringBuilder sb = new StringBuilder();

                sb.Append("username=\"");
                sb.Append(Client.UserName.Replace("\"", "\\\""));
                sb.Append("\"");

                if (!string.IsNullOrEmpty(Realm))
                {
                    sb.Append(",realm=\"");
                    sb.Append(Realm.Replace("\"", "\\\""));
                    sb.Append("\"");
                }

                sb.Append(",nonce=\"");
                sb.Append(Nonce.Replace("\"", "\\\""));
                sb.Append("\"");

                string DigestUri = "xmpp/" + Client.Domain;

                string ClientNonce = Convert.ToBase64String(XmppClient.GetRandomBytes(16));

                sb.Append(",cnonce=\"");
                sb.Append(ClientNonce.Replace("\"", "\\\""));
                sb.Append("\",nc=00000001");

                if (!string.IsNullOrEmpty(Qop))
                {
                    sb.Append(",qop=");

                    if (AuthInt)
                    {
                        sb.Append("auth-int");
                    }
                    else if (Auth)
                    {
                        sb.Append("auth");
                    }
                    else
                    {
                        sb.Append(Qop);
                    }
                }

                sb.Append(",digest-uri=\"");
                sb.Append(DigestUri);
                sb.Append("\"");

                byte[] HPass;

                if (string.IsNullOrEmpty(Client.PasswordHash))
                {
                    HPass = H(CONCAT(Client.UserName, ":", Realm, ":", Client.Password));
                    Client.PasswordHash       = Convert.ToBase64String(HPass);
                    Client.PasswordHashMethod = this.HashMethodName;
                }
                else
                {
                    HPass = Convert.FromBase64String(Client.PasswordHash);
                }

                if (string.IsNullOrEmpty(Client.BareJID))
                {
                    A1 = CONCAT(HPass, ":", Nonce, ":", ClientNonce);
                }
                else
                {
                    A1 = CONCAT(HPass, ":", Nonce, ":", ClientNonce, ":", Client.BareJID);
                }

                if (Qop == "auth")
                {
                    A2 = CONCAT("AUTHENTICATE:", DigestUri);
                }
                else
                {
                    A2 = CONCAT("AUTHENTICATE:", DigestUri, ":00000000000000000000000000000000");
                }

                string ResponseString = HEX(KD(HEX(H(A1)), CONCAT(Nonce, ":00000001:", ClientNonce, ":", Qop, ":", HEX(H(A2)))));

                sb.Append(",response=");
                sb.Append(ResponseString);

                sb.Append(",charset=utf-8");

                if (!string.IsNullOrEmpty(Client.BareJID))
                {
                    sb.Append(",authzid=\"");
                    sb.Append(Client.BareJID);
                    sb.Append("\"");
                }

                return(Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sb.ToString())));
            }
        }
Exemple #45
0
 /// <summary>
 /// Base class for XMPP Extensions.
 /// </summary>
 /// <param name="Client">XMPP Client.</param>
 public XmppExtension(XmppClient Client)
 {
     this.client = Client;
     this.client.RegisterExtension(this);
 }
Exemple #46
0
        public FrmAddUser(Dictionary <string, ListViewGroup> _dictContactGroups, bool isAdd, XmppClient xmppClient)
        {
            InitializeComponent();
            _xmppClient       = xmppClient;
            DictContactGroups = _dictContactGroups;
            foreach (var item in DictContactGroups)
            {
                cboGroup.Items.Add(item.Value);
            }

            if (!isAdd)
            {
                txtAddress.Enabled = false;
                rtMessage.Enabled  = false;
                btnAdd.Text        = "Update";
            }
            _xmppClient.OnIq += new EventHandler <IqEventArgs>(_xmppClient_OnIq);
            txtName.Text      = string.Empty;
        }
 public SaslXmppHandler(XmppClient client)
     : base(client)
 {
     // create case insensitive dictionary for easier string comparison later
     this.authenticationSets = new Dictionary<string,string>(StringComparer.InvariantCultureIgnoreCase);
 }
Exemple #48
0
        private void ChatMessageReceived(object P)
        {
            MessageEventArgs e = (MessageEventArgs)P;
            ChatView         ChatView;

            string Message    = e.Body;
            bool   IsMarkdown = false;

            foreach (XmlNode N in e.Message.ChildNodes)
            {
                if (N.LocalName == "content" && N.NamespaceURI == "urn:xmpp:content")
                {
                    string Type = XML.Attribute((XmlElement)N, "type");
                    if (Type == "text/markdown")
                    {
                        IsMarkdown = true;

                        Type = N.InnerText;
                        if (!string.IsNullOrEmpty(Type))
                        {
                            Message = Type;
                        }

                        break;
                    }
                }
            }

            foreach (TabItem TabItem in this.Tabs.Items)
            {
                ChatView = TabItem.Content as ChatView;
                if (ChatView == null)
                {
                    continue;
                }

                XmppContact XmppContact = ChatView.Node as XmppContact;
                if (XmppContact == null)
                {
                    continue;
                }

                if (XmppContact.BareJID != e.FromBareJID)
                {
                    continue;
                }

                XmppAccountNode XmppAccountNode = XmppContact.XmppAccountNode;
                if (XmppAccountNode == null)
                {
                    continue;
                }

                if (XmppAccountNode.BareJID != XmppClient.GetBareJID(e.To))
                {
                    continue;
                }

                ChatView.ChatMessageReceived(Message, IsMarkdown, this);
                return;
            }

            foreach (TreeNode Node in this.MainView.ConnectionTree.Items)
            {
                XmppAccountNode XmppAccountNode = Node as XmppAccountNode;
                if (XmppAccountNode == null)
                {
                    continue;
                }

                if (XmppAccountNode.BareJID != XmppClient.GetBareJID(e.To))
                {
                    continue;
                }

                if (XmppAccountNode.TryGetChild(e.FromBareJID, out TreeNode ContactNode))
                {
                    TabItem TabItem2 = MainWindow.NewTab(e.FromBareJID);
                    this.Tabs.Items.Add(TabItem2);

                    ChatView         = new ChatView(ContactNode);
                    TabItem2.Content = ChatView;

                    ChatView.ChatMessageReceived(Message, IsMarkdown, this);
                    return;
                }
            }
        }
Exemple #49
0
 private void FrmChat_FormClosed(object sender, FormClosedEventArgs e)
 {
     Util.ChatForms.Remove(_jid.Bare.ToLower());
     _xmppClient.MessageFilter.Remove(_jid);
     _xmppClient = null;
 }
Exemple #50
0
 /// <summary>
 /// Client providing support for server mail-extension.
 /// </summary>
 /// <param name="Client">XMPP Client to use.</param>
 public MailClient(XmppClient Client)
     : base(Client)
 {
     Client.RegisterMessageHandler("mailInfo", NamespaceMail, this.MailHandler, true);
 }
        private void ConnectToHost(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is Dictionary <string, object> Parameters))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("host", out Obj) || !(Obj is string HostName))
            {
                throw new BadRequestException();
            }

            string TabID = Request.Header["X-TabID"];

            if (string.IsNullOrEmpty(TabID))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("port", out Obj) || !(Obj is int Port) || Port < 1 || Port > 65535)
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("boshUrl", out Obj) || !(Obj is string BoshUrl))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("wsUrl", out Obj) || !(Obj is string WsUrl))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("customBinding", out Obj) || !(Obj is bool CustomBinding))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("trustServer", out Obj) || !(Obj is bool TrustServer))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("insecureMechanisms", out Obj) || !(Obj is bool InsecureMechanisms))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("storePassword", out Obj) || !(Obj is bool StorePasswordInsteadOfHash))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("sniffer", out Obj) || !(Obj is bool Sniffer))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("transport", out Obj) || !(Obj is string s2) || !Enum.TryParse <XmppTransportMethod>(s2, out XmppTransportMethod Method))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("account", out Obj) || !(Obj is string Account))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("password", out Obj) || !(Obj is string Password))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("createAccount", out Obj) || !(Obj is bool CreateAccount))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("accountName", out Obj) || !(Obj is string AccountName))
            {
                throw new BadRequestException();
            }

            this.host                       = HostName;
            this.port                       = Port;
            this.boshUrl                    = BoshUrl.Trim();
            this.wsUrl                      = WsUrl.Trim();
            this.customBinding              = CustomBinding;
            this.trustServer                = TrustServer;
            this.allowInsecureMechanisms    = InsecureMechanisms;
            this.storePasswordInsteadOfHash = StorePasswordInsteadOfHash;
            this.sniffer                    = Sniffer;
            this.transportMethod            = Method;
            this.account                    = Account;
            this.createAccount              = CreateAccount;
            this.accountHumanReadableName   = AccountName;

            if (this.password != Password)
            {
                this.password     = Password;
                this.passwordType = string.Empty;
            }

            if (this.client != null)
            {
                this.client.Dispose();
                this.client = null;
            }

            Response.StatusCode = 200;

            this.Connect(TabID);
        }
Exemple #52
0
 /// <summary>
 /// Implements a Proxy resource that allows Web clients to fetch HTTP-based resources over HTTPX.
 /// </summary>
 /// <param name="ResourceName">Resource name of proxy resource.</param>
 /// <param name="DefaultXmppClient">Default XMPP client.</param>
 /// <param name="MaxChunkSize">Max Chunk Size to use.</param>
 /// <param name="ServerlessMessaging">Serverless messaging manager.</param>
 public HttpxProxy(string ResourceName, XmppClient DefaultXmppClient, int MaxChunkSize, XmppServerlessMessaging ServerlessMessaging)
     : this(ResourceName, DefaultXmppClient, MaxChunkSize, ServerlessMessaging, null)
 {
 }