Dream, not what is, but what can be.

IFTTT - Belkin WeMo Mini Smart Plug

Created IFTTT account
Create Applet WebHook to receive web requests
Create Applet WeMo Switch
IF WebHook - Receive web request THEN WeMo Switch Turn On
IF WebHook - Receive web request THEN WeMo Switch Turn Off

Trigger by sending Post

var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://maker.ifttt.com/trigger/<EVENTNAME>/with/key/<YOURKEY>");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string result;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    result = streamReader.ReadToEnd();
}

Posted on Sunday, November 05, 2017 7:11 AM


Belkin WeMo Mini Smart Plug

Sample code to set Belkin WeMo Mini Smart Plug to on or off.
Available Commands - http://YourWemoDeviceIPAddress:49153/eventservice.xml
Device Information - http://YourWemoDeviceIPAddress:49153/setup.xml

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SmartDeviceConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            SetupWeMo();
            GetDeviceState();
			SetDeviceState(1);

            while (!Console.KeyAvailable) System.Threading.Thread.Sleep(500);
        }

        static void SetupWeMo()
        {
            bool repeat = true;

            while (repeat)
            {
                UdpClient udpClient = null;
                try
                {
                    // Creates the socket.
                    udpClient = new UdpClient(10140);
                    udpClient.Client.ReceiveTimeout = 4000;
                    IPAddress broadcastIpAddress = IPAddress.Parse("239.255.255.250");
                    IPEndPoint broadcastIpEndPoint = new IPEndPoint(broadcastIpAddress, 1900);
                    udpClient.JoinMulticastGroup(broadcastIpAddress);

                    // Sends SSDP.
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.Append("M-SEARCH * HTTP/1.1\r\n");
                    stringBuilder.Append("ST: urn:Belkin:service:basicevent:1\r\n");
                    stringBuilder.Append("MX: 1\r\n");
                    stringBuilder.Append("MAN: \"ssdp:discover\"\r\n");
                    stringBuilder.Append("HOST: 239.255.255.250:1900\r\n");
                    stringBuilder.Append("\r\n");
                    byte[] bytesToSend = Encoding.UTF8.GetBytes(stringBuilder.ToString());
                    udpClient.Send(bytesToSend, bytesToSend.Length, broadcastIpEndPoint);

                    // Receives response.
                    IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    byte[] receivedBytes = udpClient.Receive(ref remoteIpEndPoint);
                    string receivedString = Encoding.UTF8.GetString(receivedBytes);
                    Console.WriteLine(receivedString);

                    repeat = false;
                }
                catch (SocketException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    udpClient.Close();
                }
            }
        }

        static void GetDeviceState()
        {
            HttpWebRequest req = WebRequest.Create("http://" + IPADDR + ":" + PORT + "/upnp/control/basicevent1") as HttpWebRequest;
            string reqContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
            StringBuilder reqContent = new StringBuilder();
            reqContent.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            reqContent.Append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
            reqContent.Append("<s:Body>");
            reqContent.Append("<u:GetBinaryState xmlns:u=\"urn:Belkin:service:basicevent:1\">");
            reqContent.Append("</u:GetBinaryState>");
            reqContent.Append("</s:Body>");
            reqContent.Append("</s:Envelope>");
            UTF8Encoding encoding = new UTF8Encoding();

            req.ContentType = "text/xml; charset=\"utf-8\"";
            req.Headers.Add("SOAPACTION:\"urn:Belkin:service:basicevent:1#GetBinaryState\"");
            req.Method = "POST";

            using (Stream requestStream = req.GetRequestStream())
            {
                requestStream.Write(encoding.GetBytes(reqContent.ToString()), 0,
                    encoding.GetByteCount(reqContent.ToString()));
            }

            try
            {
                HttpWebResponse response = req.GetResponse() as HttpWebResponse;
                using (Stream rspStm = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(rspStm))
                    {
                        Debug.WriteLine("Response Description: " + response.StatusDescription);
                        Debug.WriteLine("Response Status Code: " + response.StatusCode);
                        Debug.WriteLine(reader.ReadToEnd());
                    }
                }
            }
            catch (System.Net.WebException ex)
            {
                Debug.WriteLine("Exception message: " + ex.Message);
                Debug.WriteLine("Response Status Code: " + ex.Status);
            }
        }

        static void SetDeviceState(DeviceState action)
        {
            HttpWebRequest req = WebRequest.Create("http://" + IPADDR + ":" + PORT + "/upnp/control/basicevent1") as HttpWebRequest;
            string reqContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
            StringBuilder reqContent = new StringBuilder();
            reqContent.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            reqContent.Append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
            reqContent.Append("<s:Body>");
            reqContent.Append("<u:SetBinaryState xmlns:u=\"urn:Belkin:service:basicevent:1\">");
            reqContent.Append("<BinaryState>");
            reqContent.Append([0 or 1]);
            reqContent.Append("</BinaryState>");
            reqContent.Append("</u:SetBinaryState>");
            reqContent.Append("</s:Body>");
            reqContent.Append("</s:Envelope>");
            UTF8Encoding encoding = new UTF8Encoding();

            req.ContentType = "text/xml; charset=\"utf-8\"";
            req.Headers.Add("SOAPACTION:\"urn:Belkin:service:basicevent:1#SetBinaryState\"");
            req.Method = "POST";

            using (Stream requestStream = req.GetRequestStream())
            {
                requestStream.Write(encoding.GetBytes(reqContent.ToString()), 0,
                    encoding.GetByteCount(reqContent.ToString()));
            }

            try
            {
                HttpWebResponse response = req.GetResponse() as HttpWebResponse;
                using (Stream rspStm = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(rspStm))
                    {
                        Debug.WriteLine("Response Description: " + response.StatusDescription);
                        Debug.WriteLine("Response Status Code: " + response.StatusCode);
                        Debug.WriteLine("responseBody: " + reader.ReadToEnd());
                    }
                }
                Debug.WriteLine("Success: " + response.StatusCode.ToString());
            }
            catch (System.Net.WebException ex)
            {
                Debug.WriteLine("Exception message: " + ex.Message);
                Debug.WriteLine("Response Status Code: " + ex.Status);
            }
        }
    }
}

Posted on Friday, November 03, 2017 2:36 PM


Android app using multiple cloud services / vendors

Created an Android app using Android Studio and Java using Google Cloud Speech API client for speech recognition, IBM Watson Conversation Service for natural language dialog, and Amazon Web Service (AWS) Polly for speech synthesis.

Posted on Thursday, October 05, 2017 6:32 AM


Android Emulator crashes when open [SOLVED]


  1. Start the Hyper-V manager

  2. Select the emulator you are trying to use

  3. Right-click, hit settings

  4. Click processorClick Compatibility

  5. Set checkbox “Migrate to a physical computer with a different processor version”




Posted on Sunday, October 01, 2017 10:07 AM


Universal Windows Platform (UWP) API's from .Net Framework

To get access to the C# API's, add two references to your project:

1) C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd
2) C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll (depends on the version of .Net that you're using)

Posted on Tuesday, July 18, 2017 8:52 AM


WPF Allow UI to update within long running method

OnPropertyChanged and Dispatcher do not update within long running method.

This code does!

void AllowUIToUpdate()
{
    DispatcherFrame frame = new DispatcherFrame();
    Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Render, new DispatcherOperationCallback(delegate (object parameter)
    {
        frame.Continue = false;
        return null;
    }), null);
    Dispatcher.PushFrame(frame);
}

Posted on Monday, July 31, 2017 10:06 AM


Play multiple audio on multiple channels using ASIO using NAudio

Play multiple audio on multiple channels using ASIO simultaneously using NAudio.

var waveProvider = new MultiplexingWaveProvider(new IWaveProvider[] { this.reader, this.reader1 }, 2);
waveProvider.ConnectInputToOutput(0, 0);
waveProvider.ConnectInputToOutput(1, 1);

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

this.asioOut = new AsioOut(comboBox1.Text);
this.asioOut.Init(waveProvider);

this.reader.Position = 0;
this.reader1.Position = 0;
this.asioOut.Play();

Posted on Wednesday, July 19, 2017 6:31 AM


Visual Studio built in Presenter Mode

Install Visual Studio Productivity Tools

Quick Launch (ctrl + Q). Simply type “PresentOn” and press enter. All of the fonts including code and environment are sized to be appropriate for presenting. When you are done, simply go back to the Quick Launch and type “PresentOff” and everything goes back to normal.

Posted on Monday, April 24, 2017 7:05 AM


Random String


private string RandomString(int length)
{
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return new string(Enumerable.Repeat(chars, length)
      .Select(s => s[random.Next(s.Length)]).ToArray());
}

Posted on Friday, April 14, 2017 6:30 AM


Web Sockets example

Code for web socket server

    public class MyEchoHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.IsWebSocketRequest)
            {
                context.AcceptWebSocketRequest(WebSocketRequestHandler);
            }
        }

        public bool IsReusable { get { return false; } }

        //Asynchronous request handler.
        public async Task WebSocketRequestHandler(AspNetWebSocketContext ctx)
        {
            //Gets the current WebSocket object.
            WebSocket socket = ctx.WebSocket;

            await socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Connected to the echo server!")), WebSocketMessageType.Text, true, CancellationToken.None);

            WebSocketReceiveResult result = null;

            ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[20480]);
            while (true)
            {
                using (var ms = new MemoryStream())
                {
                    do
                    {
                        result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                        ms.Write(buffer.Array, buffer.Offset, result.Count);
                    }
                    while (!result.EndOfMessage);

                    ms.Seek(0, SeekOrigin.Begin);

                    if (result.MessageType == WebSocketMessageType.Text)
                    {
                        var sr = new StreamReader(ms);
                        var str = sr.ReadToEnd();
                        data = new JavaScriptSerializer().Deserialize<TimingData>(str.Substring(0, str.LastIndexOf("}") + 1));

                        string response = svc.TimingDataPost(data);
                        byte[] toBytes = Encoding.ASCII.GetBytes(response);
                        await socket.SendAsync(new ArraySegment<byte>(toBytes, 0, toBytes.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);
                    }
                    else if (result.CloseStatus != null)
                    {
                        await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Result Goodbye", CancellationToken.None);
                        return;
                    }
                }
            }
        }
    }

Code for web socket client

<body>
<p>
<input id="txtInput" type="text" value="" />
<input type="button" value="Send" id="btnSend" />
<input type="button" value="Close" id="btnClose" />
</p>
<div id="output">

</div>

<script type="text/javascript">
<!-- ws / wss (SSL) -->
var url = "wss://<service>/MyEchoHandler.ashx";

var webSocket = new WebSocket(url);

var inputTextBox = document.getElementById("txtInput");
document.getElementById("btnSend").addEventListener("click", function () { webSocket.send(inputTextBox.value); });
document.getElementById("btnClose").addEventListener("click", function () { webSocket.close(); });

var outputDiv = document.getElementById("output");
function appendToDiv(text) {
var newElement = document.createElement("p");
newElement.appendChild(document.createTextNode("[" + new Date().toLocaleDateString() + "]" + text));
outputDiv.insertBefore(newElement, outputDiv.firstChild);
}

webSocket.onopen = function () { appendToDiv("Socket Opened!"); };
webSocket.onmessage = function (event) { appendToDiv(event.data); };
webSocket.onerror = function () { appendToDiv("Socket error!"); };
webSocket.onclose = function (event) { appendToDiv("Socket closed with message '" + event.reason + "'."); };
</script>
</body>

Posted on Tuesday, February 07, 2017 6:30 AM