Click here to Skip to main content
15,881,812 members
Articles / Programming Languages / C#

Robot Alarm Clock

Rate me:
Please Sign up or sign in to vote.
4.96/5 (9 votes)
15 Sep 2013CPOL10 min read 27.2K   2.8K   14  
Bluetooth robotic alarm clock using C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Windows.Forms;
using Microsoft.Win32;

namespace SpheroAlarmClock
{
	class SerialStatus
	{
		public List<SerialPortData> SerialPortList = new List<SerialPortData>();	// List of serial ports found in registry
		public List<ComPortData> BluetoothPortList = new List<ComPortData>();		// List of Bluetooth ports to be displayed
		public void ExecuteSerialStatus()
		{
			SerialPortList.Clear();
			BluetoothPortList.Clear();

			SerialPortList = populateSerialPorts();					// get all serial port entries in registry
			BluetoothPortList = processCommPorts(SerialPortList);	// process serial port entries to Bluetooth Port list (display list)
		}

		List<SerialPortData> populateSerialPorts()
		{
			ManagementObjectCollection ManObjReturn;
			ManagementObjectSearcher ManObjSearch;
			ManObjSearch = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
			ManObjReturn = ManObjSearch.Get();
			string DeviceID, PortName, PortDescription, PortType;
			List<SerialPortData> BluetoothPortList = new List<SerialPortData>();

			foreach (ManagementObject ManObj in ManObjReturn)
			{
				int s = ManObj.Properties.Count;
				if (ManObj != null && ManObj["Caption"].ToString().Contains("(COM"))
				{
					SerialPortData SPEntry = new SerialPortData();
					PortName = ManObj["Caption"].ToString().Split('(', ')')[1];
					PortType = ManObj["DeviceID"].ToString().Split('\\')[0];
					PortDescription = (string)(ManObj["Description"]);

					SPEntry.PortName = PortName;
					SPEntry.PortType = PortType;
					if ((PortType != null) && (PortType.Length > 0) && PortType == "BTHENUM")               // is device BlueTooth?
					{
						DeviceID = (string)(ManObj["DeviceID"]);
						SPEntry.BluetoothAddress = GetBTAfromDeviceID(DeviceID);  // get BlueTooth MAC address from DeviceID entry
						BluetoothPortList.Add(SPEntry);
					}
				}
			}
			return BluetoothPortList;
		}

		// takes serialport array and mine for more data. Output is com port array
		List<ComPortData> processCommPorts(List<SerialPortData> AllSerialPortData)
		{
			string BTPort;
			List<ComPortData> AllComPortData = new List<ComPortData>();        // array of ComPortData entries

			foreach (SerialPortData SerialPortDataEntry in AllSerialPortData)
			{
				ComPortData ComPortDataEntry = new ComPortData();    // ComPortData entry
				ComPortDataEntry.ComName = SerialPortDataEntry.PortName;
				if ((SerialPortDataEntry.PortType == "BTHENUM"))               // is device BlueTooth?
				{
					if (SerialPortDataEntry.BluetoothAddress != "000000000000")	// if BTA is zeros, this is a 'spare' bt port
					{
						// get BlueToooth name from registry
						BTPort = MineRegistryForBluetoothAddress("SYSTEM\\CurrentControlSet\\services\\BTHPORT\\Parameters\\LocalServices", SerialPortDataEntry.BluetoothAddress);
						if (BTPort != null)
						{
							ComPortDataEntry.BluetoothName = BTPort;
							AllComPortData.Add(ComPortDataEntry);
						}
					}
				}
			}
			return AllComPortData;
		}

		static string MineRegistryForBluetoothAddress(string startKeyPath, string BluetoothAddress)
		{
			using (RegistryKey currentKey = Registry.LocalMachine)
			{
				try
				{
					using (RegistryKey currentSubKey = currentKey.OpenSubKey(startKeyPath))
					{
						string[] currentSubkeys = currentSubKey.GetSubKeyNames();
						if (currentSubkeys.Contains("0"))
						{
							foreach (string subkey in currentSubkeys)
							{
								object AssocBdAddr = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + startKeyPath + "\\" + subkey, "AssocBdAddr", null);
								StringBuilder sb = new StringBuilder();
								for (int i = 5; i >= 0; i--)
									sb.Append(((byte[])AssocBdAddr)[i].ToString("X2"));

								string hexString = sb.ToString();
								if ((string)hexString == BluetoothAddress)
								{
									object Enabled = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + startKeyPath + "\\" + subkey, "Enabled", null);
									if ((int)Enabled == 1)
									{
										object ServiceName = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + startKeyPath + "\\" + subkey, "ServiceName", null);
										return (string)ServiceName;
									}
								}
							}
						}
						else
						{
							foreach (string strSubKey in currentSubkeys)
						    {
						        string BTP = MineRegistryForBluetoothAddress(startKeyPath + "\\" + strSubKey, BluetoothAddress);
						        if (BTP != null)
						            return BTP;
						    }
						}
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine("Error accessing key '{0}' with {1} Skipping..", startKeyPath, ex);
					MessageBox.Show("Error accessing key " + startKeyPath + "  with " + ex + " Skipping..");
				}
				return "";
			}
		}

		public string GetBTAfromDeviceID(string DevID)
		{
			string[] dataArray = DevID.Split('&');
			string[] BTA = dataArray[dataArray.Length - 1].Split('_');
			return BTA[0];
		}

	}

	class SerialPortData
	{
		public string PortName;
		public string PortType;
		public string BluetoothAddress;

		public SerialPortData()
		{
			PortName = null;
			PortType = null;
			BluetoothAddress = null;
		}
	}

	class ComPortData
	{
		public string ComName;
		public string BluetoothName;

		public ComPortData()
		{
			ComName = null;
			BluetoothName = null;
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions