Created
October 14, 2013 00:25
-
-
Save thdxr/6968939 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace Bulb | |
{ | |
public class Controller | |
{ | |
private UdpClient _client; | |
private int _brightness; | |
private byte _color; | |
public Controller(string ip, int port = 8899) | |
{ | |
_client = new UdpClient(ip, port); | |
TurnOn(); | |
_brightness = 0; | |
SetBrightness(9); | |
_color = 255; | |
SetColor(0); | |
} | |
public void TurnOn() | |
{ | |
Send(On); | |
} | |
public void TurnOff() | |
{ | |
Send(Off); | |
} | |
public void SetBrightness(int i) | |
{ | |
if(i < 0 || i>9) return; | |
var f = i < _brightness ? Dim : new Action(Brighten); | |
while (_brightness != i) | |
{ | |
f(); | |
} | |
} | |
public void Brighten() | |
{ | |
Send(BrightnessUp); | |
if (_brightness < 10) | |
_brightness++; | |
} | |
public void Dim() | |
{ | |
Send(BrightnessDown); | |
if (_brightness > 0) | |
_brightness--; | |
} | |
public void SetColor(byte i) | |
{ | |
var copy = (byte[])Color.Clone(); | |
copy[1] = i; | |
Send(copy); | |
_color = i; | |
} | |
private void Send(byte[] cmd) | |
{ | |
_client.Send(cmd, cmd.Length); | |
Thread.Sleep(100); | |
} | |
private static readonly byte[] On = { 0x22, 0x0, 0x55 }; | |
private static readonly byte[] Off = { 0x21, 0x0, 0x55 }; | |
private static readonly byte[] Color = { 0x20, 0x00, 0x55 }; | |
private static readonly byte[] BrightnessUp = { 0x23, 0x00, 0x55 }; | |
private static readonly byte[] BrightnessDown = { 0x24, 0x00, 0x55 }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment