From: <che...@us...> - 2008-02-16 15:47:12
|
Revision: 1372 http://mp-plugins.svn.sourceforge.net/mp-plugins/?rev=1372&view=rev Author: chef_koch Date: 2008-02-16 07:46:56 -0800 (Sat, 16 Feb 2008) Log Message: ----------- added MP2version Added Paths: ----------- trunk/plugins/FritzBox/MP2version/ trunk/plugins/FritzBox/MP2version/CallMonitor.cs trunk/plugins/FritzBox/MP2version/CallMonitor.csproj trunk/plugins/FritzBox/MP2version/CallMonitor.plugin trunk/plugins/FritzBox/MP2version/HelperClasses/ trunk/plugins/FritzBox/MP2version/HelperClasses/CallAction.cs trunk/plugins/FritzBox/MP2version/HelperClasses/Caller.cs trunk/plugins/FritzBox/MP2version/HelperClasses/ICallMonitor.cs trunk/plugins/FritzBox/MP2version/HelperClasses/IListener.cs trunk/plugins/FritzBox/MP2version/ListenerBuilder.cs trunk/plugins/FritzBox/MP2version/Listeners/ trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/ trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/BlueTooth_USB.cs trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/BlueTooth_USB.csproj trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/BlueTooth_USB.plugin trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/Helper/ trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/Helper/ATcommand.cs trunk/plugins/FritzBox/MP2version/Listeners/FritzBox/ trunk/plugins/FritzBox/MP2version/Listeners/FritzBox/FritzBox.cs trunk/plugins/FritzBox/MP2version/Listeners/FritzBox/FritzBox.csproj trunk/plugins/FritzBox/MP2version/Listeners/FritzBox/FritzBox.plugin trunk/plugins/FritzBox/MP2version/Listeners/FritzBox/Properties/ trunk/plugins/FritzBox/MP2version/Listeners/FritzBox/Properties/AssemblyInfo.cs trunk/plugins/FritzBox/MP2version/Properties/ trunk/plugins/FritzBox/MP2version/Properties/AssemblyInfo.cs Added: trunk/plugins/FritzBox/MP2version/CallMonitor.cs =================================================================== --- trunk/plugins/FritzBox/MP2version/CallMonitor.cs (rev 0) +++ trunk/plugins/FritzBox/MP2version/CallMonitor.cs 2008-02-16 15:46:56 UTC (rev 1372) @@ -0,0 +1,278 @@ +using System; +using System.Collections.Generic; +using System.Text; +using MediaPortal.Core.PluginManager; +using MediaPortal.Core; +using MediaPortal.Core.Logging; +using MediaPortal.Core.Database.Interfaces; +using MediaPortal.Core.MediaManager.Views; + +namespace CallMonitor +{ + public class CallMonitor : IPlugin, IAutoStart, ICallMonitor + { + ILogger Logger; + + + IDatabase _callDatabase; + List<ListenerBuilder> _listeners; + + /// <summary> + /// Initializes a new instance of the <see cref="CallMonitor"/> class. + /// </summary> + public CallMonitor() + { + Logger = ServiceScope.Get<ILogger>(); + } + + #region IPlugin Members + public void Initialize(string id) + { + // Get all Importer plugins + try + { + _listeners = ServiceScope.Get<IPluginManager>().GetAllPluginItems<ListenerBuilder>("/CallMonitor/Listeners"); + } + catch (Exception ex) + { + Logger.Error("FritzBox: CallMonitor: {0}", ex, "FEHLER"); + } + } + + public void Dispose() + { + } + #endregion + + #region IImporterManager Members + + /// <summary> + /// Registers the specified listener. + /// </summary> + /// <param name="listener">The listener.</param> + public void Register(IListener listener) + { + // Use plugin space + //if (!_listeners.Contains(listener)) + //{ + // _listeners.Add(listener); + //} + } + + /// <summary> + /// Unregisters the listener + /// </summary> + /// <param name="listener">The listener.</param> + public void UnRegister(IListener listener) + { + //if (_listeners.Contains(listener)) + //{ + // _listeners.Remove(listener); + //} + } + + /// <summary> + /// Gets the registered listeners. + /// </summary> + /// <value>The registered listeners.</value> + public List<IListener> Listeners + { + get + { + List<IListener> listeners = new List<IListener>(); + foreach (ListenerBuilder listenerBuilder in _listeners) + { + listeners.Add(listenerBuilder.Listener); + } + return listeners; + } + } + + /// <summary> + /// Gets the listener for the specific name + /// </summary> + /// <param name="name">The name.</param> + /// <returns></returns> + public IListener GetListenerByName(string name) + { + foreach (ListenerBuilder listenerBuilder in _listeners) + { + if (String.Compare(listenerBuilder.Name, name, true) == 0) + return listenerBuilder.Listener; + } + return null; + } + #endregion + + + /// <summary> + /// Initializes this instance. + /// </summary> + private void Initialize() { } + + /// <summary> + /// Startups this instance. + /// </summary> + public void Startup() + { + ServiceScope.Add<ICallMonitor>(this); + + try + { + foreach (IListener listener in Listeners) + { + listener.Start(); + } + } + catch (Exception ex) + { + Logger.Error("FritzBox: CallMonitor: {0}", ex, "FEHLER"); + } + + Initialize(); + } + + + + + + + + /// <summary> + /// Creates the picture database. + /// </summary> + void CreateCallsDatabase() + { + try + { + IDatabaseBuilderFactory builderFactory = ServiceScope.Get<IDatabaseBuilderFactory>(); + IDatabaseFactory factory = builderFactory.CreateFromId("Calls"); + + _callDatabase = factory.Open("Calls"); + + _callDatabase.Add("Date", typeof(DateTime), 1024); + _callDatabase.Add("CallerId", typeof(string), 1024); + //_callDatabase.Add("CameraModel", typeof(string), 40); + //_callDatabase.Add("EquipmentMake", typeof(string), 40); + //_callDatabase.Add("ExposureCompensation", typeof(string), 1024); + //_callDatabase.Add("ExposureTime", typeof(string), 1024); + //_callDatabase.Add("Flash", typeof(string), 40); + //_callDatabase.Add("Fstop", typeof(string), 40); + //_callDatabase.Add("ImgDimensions", typeof(string), 40); + //_callDatabase.Add("title", typeof(string), 60); + //_callDatabase.Add("MeteringMod", typeof(string), 1024); + //_callDatabase.Add("Resolutions", typeof(string), 1024); + //_callDatabase.Add("ShutterSpeed", typeof(string), 1024); + //_callDatabase.Add("ViewComment", typeof(string), 1024); + //_callDatabase.Add("ISOSpeed", typeof(string), 1024); + //_callDatabase.Add("Orientation", typeof(int)); + //_callDatabase.Add("PictureTags", typeof(List<string>), 1024); + //_callDatabase.Add("contentURI", typeof(string), 1024); + //_callDatabase.Add("CoverArt", typeof(string), 1024); + //_callDatabase.Add("Updated", typeof(string), 1); + //_callDatabase.Add("path", typeof(string), 1024); + //_callDatabase.Add("dateAdded", typeof(DateTime)); + + //get date/time of last import done.... + //Query lastDateQuery = new Query(); + //lastDateQuery.Sort = SortOrder.Descending; + //lastDateQuery.SortFields.Add("dateAdded"); + //lastDateQuery.Limit = 1; + //List<IDbItem> lastItems = _callDatabase.Query(lastDateQuery); + //if (lastItems.Count == 0) + // _lastImport = DateTime.MinValue; + //else + // _lastImport = (DateTime)lastItems[0]["dateAdded"]; + } + catch (Exception ex) + { + ServiceScope.Get<ILogger>().Info("callmonitor:error CreatePictureDatabase"); + ServiceScope.Get<ILogger>().Error(ex); + } + } + } +} + + + + + + + + + //public void Startup() + //{ + // try + // { + // IPluginManager pluginManager = ServiceScope.Get<IPluginManager>(); + + + + // foreach (IListener plugin in pluginManager.GetAllPluginItems<IListener>("/CallMonitor/Listeners")) + // { + // //plugin.Startup(); + // } + + // ServiceScope.Add<ICallMonitor>(this); + + // List<string> strL = new List<string>(); + // strL.Add("/AutoStart"); + // strL.Add("/Media/Providers"); + // strL.Add("/CallMonitor/Listeners"); + + + // foreach (string str in strL) + // { + // string count = ServiceScope.Get<IPluginManager>().GetAllPluginItems<IPlugin>(str).Count.ToString(); + // ServiceScope.Get<ILogger>().Info("FritzBox: CallMonitor: {0} count: {1}", str, count); + // } + + + // foreach (IListener listener in ServiceScope.Get<IPluginManager>().GetAllPluginItems<IListener>("/")) + // { + // ServiceScope.Get<ILogger>().Info("FritzBox: CallMonitor: register {0}", listener.ToString()); + // ServiceScope.Get<ICallMonitor>().Register(listener); + // } + + + // foreach (IPlugin listener in ServiceScope.Get<IPluginManager>().GetAllPluginItems<IPlugin>("/AutoStart")) + // { + // ServiceScope.Get<ILogger>().Info("FritzBox: CallMonitor: register {0}", listener.ToString()); + // } + // ServiceScope.Get<ILogger>().Info("FritzBox: IPluginInfo: AutoStart DONE "); + // foreach (IPlugin listener in ServiceScope.Get<IPluginManager>().GetAllPluginItems<IPlugin>("/Media/Providers")) + // { + // ServiceScope.Get<ILogger>().Info("FritzBox: CallMonitor: register {0}", listener.ToString()); + // } + // ServiceScope.Get<ILogger>().Info("FritzBox: IPluginInfo: Media/Providers DONE "); + // foreach (IPlugin listener in ServiceScope.Get<IPluginManager>().GetAllPluginItems<IPlugin>("/Media/Providers")) + // { + // ServiceScope.Get<ILogger>().Info("FritzBox: CallMonitor: register {0}", listener.ToString()); + // } + // ServiceScope.Get<ILogger>().Info("FritzBox: IPluginInfo: Media/Providers DONE "); + // foreach (IPlugin listener in ServiceScope.Get<IPluginManager>().GetAllPluginItems<IPlugin>("//")) + // { + // ServiceScope.Get<ILogger>().Info("FritzBox: CallMonitor: register {0}", listener.ToString()); + // } + // ServiceScope.Get<ILogger>().Info("FritzBox: IPluginInfo: Listeners DONE "); + + + + // ServiceScope.Get<ILogger>().Info("FritzBox: CallMonitor: foreach (IListener listener in ServiceScope.Get<IPluginManager>().GetAllPluginItems<IListener>()"); + + + + + + // foreach (IListener listener in ServiceScope.Get<IPluginManager>().GetAllPluginItems<IListener>("/Media/Providers")) + // { + // ServiceScope.Get<ILogger>().Info("FritzBox: CallMonitor: register {0}", listener.Title); + // ServiceScope.Get<ICallMonitor>().Register(listener); + // } + // //ServiceScope.Get<ILogger>().Info("FritzBox: CallMonitor: Startup() finished {0} eintr\xE4ge", _listeners.Count.ToString()); + // } + // catch (Exception ex) + // { + // ServiceScope.Get<ILogger>().Error("FritzBox: CallMonitor: {0}", ex, "kneuk"); + // } + //} \ No newline at end of file Added: trunk/plugins/FritzBox/MP2version/CallMonitor.csproj =================================================================== --- trunk/plugins/FritzBox/MP2version/CallMonitor.csproj (rev 0) +++ trunk/plugins/FritzBox/MP2version/CallMonitor.csproj 2008-02-16 15:46:56 UTC (rev 1372) @@ -0,0 +1,71 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>8.0.50727</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{131A0BFD-AF34-4AEB-8A10-7330FE83811E}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>CallMonitor</RootNamespace> + <AssemblyName>CallMonitor</AssemblyName> + <StartupObject> + </StartupObject> + <SignAssembly>false</SignAssembly> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\x86\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <PlatformTarget>x86</PlatformTarget> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\x86\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <PlatformTarget>x86</PlatformTarget> + </PropertyGroup> + <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> + <ItemGroup> + <Compile Include="ListenerBuilder.cs" /> + <Compile Include="HelperClasses\ICallMonitor.cs" /> + <Compile Include="HelperClasses\IListener.cs" /> + <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="CallMonitor.cs" /> + <Compile Include="HelperClasses\Caller.cs" /> + <Compile Include="HelperClasses\CallAction.cs" /> + </ItemGroup> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Data" /> + <Reference Include="System.Xml" /> + </ItemGroup> + <ItemGroup> + <None Include="CallMonitor.plugin" /> + </ItemGroup> + <PropertyGroup> + <PostBuildEvent>xcopy /Y "$(ProjectDir)$(ProjectName).plugin" "$(SolutionDir)$(SolutionName)\$(OutDir)Plugins\$(ProjectName)\" +xcopy /Y "$(TargetDir)CallMonitor.dll" "$(SolutionDir)$(SolutionName)\$(OutDir)Plugins\$(ProjectName)\"</PostBuildEvent> + </PropertyGroup> + <ItemGroup> + <ProjectReference Include="..\MediaPortal.Core\MediaPortal.Core.csproj"> + <Project>{52E587D0-A274-44DA-8846-8EEAF5414923}</Project> + <Name>MediaPortal.Core</Name> + </ProjectReference> + </ItemGroup> +</Project> \ No newline at end of file Added: trunk/plugins/FritzBox/MP2version/CallMonitor.plugin =================================================================== --- trunk/plugins/FritzBox/MP2version/CallMonitor.plugin (rev 0) +++ trunk/plugins/FritzBox/MP2version/CallMonitor.plugin 2008-02-16 15:46:56 UTC (rev 1372) @@ -0,0 +1,22 @@ +<Plugin name = "CallMonitor" + author = "Frodo" + copyright = "GPL" + description = "CallMonitor"> + + <Manifest> + <Identity name = "CallMonitor.CallMonitor"/> + </Manifest> + + <Runtime> + <Import assembly = "CallMonitor.dll"> + <Builder name = 'Listener' class = 'CallMonitor.ListenerBuilder'/> + </Import> + </Runtime> + + <Register location = "/AutoStart"> + <Class id = "CallMonitor" class = "CallMonitor.CallMonitor" insertbefore = "DirectxGui"/> + </Register> + <Register location = "/Services"> + <Class id = "ICallMonitor" class = "CallMonitor.CallMonitor"/> + </Register> +</Plugin> \ No newline at end of file Added: trunk/plugins/FritzBox/MP2version/HelperClasses/CallAction.cs =================================================================== --- trunk/plugins/FritzBox/MP2version/HelperClasses/CallAction.cs (rev 0) +++ trunk/plugins/FritzBox/MP2version/HelperClasses/CallAction.cs 2008-02-16 15:46:56 UTC (rev 1372) @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Text; +using MediaPortal.Core.Logging; + +namespace CallMonitor +{ + public class CallAction + { + public enum CallType + { + Incoming, + Outgoing, + ConnectionStarted, + ConnectionClosed, + } + + public CallType type; + public DateTime time = DateTime.MinValue; + public Caller caller = new Caller(); + public string msn = string.Empty; + + public void WriteToLog() + { + ILogger log = MediaPortal.Core.ServiceScope.Get<ILogger>(); + + log.Info("CallAction Info:"); + log.Info(" CallType: {0}", this.type.ToString()); + log.Info(" Date: {0}", this.time.ToShortDateString()); + log.Info(" Time: {0}", this.time.ToShortTimeString()); + log.Info(" Caller: {0}", this.caller.ID); + log.Info(" MSN: {0}", this.msn); + } + } +} \ No newline at end of file Added: trunk/plugins/FritzBox/MP2version/HelperClasses/Caller.cs =================================================================== --- trunk/plugins/FritzBox/MP2version/HelperClasses/Caller.cs (rev 0) +++ trunk/plugins/FritzBox/MP2version/HelperClasses/Caller.cs 2008-02-16 15:46:56 UTC (rev 1372) @@ -0,0 +1,89 @@ +#region Copyright (C) 2005-2007 Team MediaPortal + +/* + * Copyright (C) 2005-2007 Team MediaPortal + * http://www.team-mediaportal.com + * + * This Program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * This Program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GNU Make; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + * http://www.gnu.org/copyleft/gpl.html + * + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.Text; + +namespace CallMonitor +{ + public class Caller + { + string _id; + string _name; + bool _show; + + public Caller() + { + this._id = ""; + this._name = ""; + this._show = true; + } + + public Caller(string id, string name, bool show) + { + this._id = id; + this._name = name; + this._show = show; + } + + public string ID + { + get + { + return _id; + } + set + { + _id = value; + } + } + + public string Name + { + get + { + return _name; + } + set + { + _name = value; + } + } + + public bool Show + { + get + { + return _show; + } + set + { + _show = value; + } + } + + } +} Added: trunk/plugins/FritzBox/MP2version/HelperClasses/ICallMonitor.cs =================================================================== --- trunk/plugins/FritzBox/MP2version/HelperClasses/ICallMonitor.cs (rev 0) +++ trunk/plugins/FritzBox/MP2version/HelperClasses/ICallMonitor.cs 2008-02-16 15:46:56 UTC (rev 1372) @@ -0,0 +1,36 @@ + +using System; +using System.Collections.Generic; + +namespace CallMonitor +{ + public interface ICallMonitor + { + /// <summary> + /// Registers a new listener with the listener manager + /// </summary> + /// <param name="listener">The Listener.</param> + [Obsolete("Listeners should be registered via the Plugin space /CallMonitor/Listeners")] + void Register(IListener listener); + + /// <summary> + /// Unregisters an listener with the listener manager + /// </summary> + /// <param name="listener">The Listener.</param> + [Obsolete("Listeners should be registered via the Plugin space /CallMonitor/Listeners")] + void UnRegister(IListener listener); + + /// <summary> + /// Gets a list of all registered listeners. + /// </summary> + /// <value>The registered listeners.</value> + List<IListener> Listeners { get;} + + /// <summary> + /// Gets the listener for the specific name + /// </summary> + /// <param name="name">The name.</param> + /// <returns></returns> + IListener GetListenerByName(string name); + } +} Added: trunk/plugins/FritzBox/MP2version/HelperClasses/IListener.cs =================================================================== --- trunk/plugins/FritzBox/MP2version/HelperClasses/IListener.cs (rev 0) +++ trunk/plugins/FritzBox/MP2version/HelperClasses/IListener.cs 2008-02-16 15:46:56 UTC (rev 1372) @@ -0,0 +1,19 @@ + +namespace CallMonitor +{ + /// <summary> + /// interface for a listener + /// </summary> + public interface IListener + { + ///// <summary> + ///// Gets the listener name. + ///// </summary> + ///// <value>The listener name.</value> + //string Name { get;} + + void Start(); + void Stop(); + bool IsActive(); + } +} Added: trunk/plugins/FritzBox/MP2version/ListenerBuilder.cs =================================================================== --- trunk/plugins/FritzBox/MP2version/ListenerBuilder.cs (rev 0) +++ trunk/plugins/FritzBox/MP2version/ListenerBuilder.cs 2008-02-16 15:46:56 UTC (rev 1372) @@ -0,0 +1,134 @@ + +using System; +using System.IO; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using MediaPortal.Core; +using MediaPortal.Core.Logging; +using MediaPortal.Core.PluginManager; +using MediaPortal.Core.Importers; +using MediaPortal.Core.MediaManager; + +namespace CallMonitor +{ + class ListenerBuilder : IPluginBuilder + { + #region variables + INodeItem _item; + IListener _listenerInstance; + #endregion + + #region IPluginBuilder methods + public object BuildItem(object caller, INodeItem item, ArrayList subItems) + { + ListenerBuilder builder = new ListenerBuilder(); + builder._item = item; + + return builder; + } + #endregion + + #region IListenerBuilder + /// <summary> + /// Gets the importer name. + /// </summary> + /// <value>The importer name.</value> + public string Name + { + get { return _item.Id; } + } + + /// <summary> + /// Gets the Listener + /// </summary> + /// <value>The Listener instance.</value> + public IListener Listener + { + get + { + Build(); + return _listenerInstance; + } + } + + /// <summary> + /// Called by the importer manager when a full-import needs to be done from the folder + /// </summary> + /// <param name="folder">The folder.</param> + //public void ImportFolder(string folder, DateTime since) + //{ + // List<string> availableFiles = new List<string>(); + // Import(folder, ref availableFiles, since); + + // if (availableFiles.Count > 0) + // { + // Build(); + // foreach (string filename in availableFiles) + // { + // _importerInstance.FileImport(filename); + // } + // } + //} + + /// <summary> + /// Called by the importer manager after it detected that a file was deleted + /// This gives the importer a change to update the database + /// </summary> + /// <param name="file">The filename of the deleted file.</param> + //public void FileDeleted(string filename) + //{ + // if (_extensions.Contains(Path.GetExtension(filename).ToLower())) + // { + // Build(); + // _importerInstance.FileDeleted(filename); + // } + //} + + /// <summary> + /// Called by the importer manager after it detected that a file was created + /// This gives the importer a change to update the database + /// </summary> + /// <param name="file">The filename of the new file.</param> + //public void FileCreated(string filename) + //{ + // if (_extensions.Contains(Path.GetExtension(filename).ToLower())) + // { + // Build(); + // _importerInstance.FileCreated(filename); + // } + //} + + /// <summary> + /// Called by the importer manager after it detected that a file was changed + /// This gives the importer a change to update the database + /// </summary> + /// <param name="file">The filename of the changed file.</param> + //public void FileChanged(string filename) + //{ + // if (_extensions.Contains(Path.GetExtension(filename).ToLower())) + // { + // Build(); + // _importerInstance.FileChanged(filename); + // } + //} + #endregion + + #region Private + private void Build() + { + if (_listenerInstance == null) + { + try + { + _listenerInstance = (IListener)_item.CreateObject(_item["class"]); + } + catch (Exception e) + { + ServiceScope.Get<ILogger>().Error(e.ToString() + "Can't create importer : " + _item.Id); + } + } + } + #endregion + } +} Added: trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/BlueTooth_USB.cs =================================================================== --- trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/BlueTooth_USB.cs (rev 0) +++ trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/BlueTooth_USB.cs 2008-02-16 15:46:56 UTC (rev 1372) @@ -0,0 +1,1225 @@ +using System.IO; +using MediaPortal.Core; +using MediaPortal.Core.Threading; + +using MediaPortal.Core.PluginManager; + +using CallMonitor; +using System; +using MediaPortal.Core.Logging; + + + + + +using System; +using System.Collections.Generic; +using System.ComponentModel; +//using System.Data; +//using System.Drawing; +using System.Text; +//using System.Windows.Forms; +using System.IO.Ports; + +using C4F.DevKit.Bluetooth.SerialPortProfile; +using System.Net.Sockets; +using System.Threading; + + +namespace CallMonitor.Listeners +{ + public class BlueTooth_USB : IPlugin, IListener + { + #region variables + + BluetoothSPPManager spp; + + public event phoneMessageHandler message; + public delegate void phoneMessageHandler(string message); + + public delegate void signalStrengthHandler(string message); + public delegate void callerIdHandler(string message); + public delegate void modeHandler(string message); + public delegate void batteryStatusHandler(string message); + public delegate void volumeHandler(string message); + + + #region Public Events and Delegates + + /// <summary> + /// This represents the method that will be raised when data is detected + /// on the port. + /// </summary> + /// <param name="sender">The sender of this event.</param> + /// <param name="e">EventArgs object containing information about the + /// event.</param> + public delegate void DataDetectedOnSerialPortEventHandler( + object sender, EventArgs e); + + /// <summary> + /// This represents the method that will be raised when data is detected + /// on the NetworkStream. + /// </summary> + /// <param name="sender">The sender of this event.</param> + /// <param name="e">EventArgs object containing information about the + /// event.</param> + public delegate void DataDetectedFromRemoteDeviceEventHandler( + object sender, EventArgs e); + + /// <summary> + /// This event will be raised when incoming data is detected on the port + /// (to be sent to the NetworkStream). + /// </summary> + public event DataDetectedOnSerialPortEventHandler + DataDetectedOnSerialPort; + + /// <summary> + /// This event will be raised when incoming data is detected on the + /// NetworkStream (to be sent to the port). + /// </summary> + public event DataDetectedFromRemoteDeviceEventHandler + DataDetectedFromRemoteDevice; + + #endregion + + ILogger Logger; + + + + + List<string> _ports = new List<string>(); + + + + + + + int _selectedPort = -1; + int _signalStrength = int.MinValue; + string _PhoneNumber = string.Empty; + string _name = string.Empty; + int _volumeLevel = -1; + int _powerLevel = -1; + + + + int _mode = -1; + + + int maxNotifies = 20; + int notifyCount = 0; + + bool stopThread = false; + + + #endregion + + #region Private Fields + /// <summary> + /// Name of the port which will be used for communication. + /// </summary> + private string portName; + + /// <summary> + /// SerialPort object representing the port which will be used for + /// communication. + /// </summary> + private SerialPort serialPort; + + /// <summary> + /// NetworkStream which will be used for communication. + /// </summary> + private NetworkStream networkStream; + + /// <summary> + /// Thread which will listen for DataDetectedFromRemoteDevice event. + /// </summary> + private Thread serialCommEventThread; + + + + + #region Serial Port Settings + + /// <summary> + /// Serial baud rate. + /// </summary> + private int baudRate = DEFAULT_BAUD_RATE; + + /// <summary> + /// Standard length of data bits per byte. + /// </summary> + private int dataBits = DEFAULT_DATA_BITS; + + /// <summary> + /// Parity-checking protocol. + /// </summary> + private Parity parity = DEFAULT_PARITY; + + /// <summary> + /// A byte that replaces invalid bytes in a data stream when a parity + /// error occurs. + /// </summary> + private byte parityReplace = DEFAULT_PARITY_REPLACE; + + /// <summary> + /// The standard number of stopbits per byte. + /// </summary> + private StopBits stopBits = DEFAULT_STOP_BITS; + + /// <summary> + /// The size of the SerialPort input buffer. + /// </summary> + private int readBufferSize = DEFAULT_READBUFFER_SIZE; + + /// <summary> + /// The number of milliseconds before a time-out occurs when a read + /// operation does not finish. + /// </summary> + private int readTimeout = DEFAULT_READ_TIMEOUT; + + /// <summary> + /// The size of the SerialPort output buffer. + /// </summary> + private int writeBufferSize = DEFAULT_WRITEBUFFER_SIZE; + + /// <summary> + /// The number of milliseconds before a time-out occurs when a write + /// operation does not finish. + /// </summary> + private int writeTimeout = DEFAULT_WRITE_TIMEOUT; + + /// <summary> + /// The byte encoding for pre- and post-transmission conversion of text. + /// </summary> + private Encoding encoding = ASCIIEncoding.ASCII; + + #endregion + + #endregion + + #region Private Constants + + /// <summary> + /// The maximum length of data bits per byte. + /// </summary> + private const int MAX_DATA_BITS = 8; + + /// <summary> + /// The minimum length of data bits per byte. + /// </summary> + private const int MIN_DATA_BITS = 5; + + #endregion + + #region Public Constants + + //Default values. + + /// <summary> + /// The default value for serial baud rate is 9600 bits per second (bps). + /// </summary> + public const int DEFAULT_BAUD_RATE = 0x2580; + + /// <summary> + /// The default value for standard length of data bits per byte is 8. + /// </summary> + public const int DEFAULT_DATA_BITS = 8; + + /// <summary> + /// The default value for Parity-checking protocol is None. + /// </summary> + public const Parity DEFAULT_PARITY = Parity.None; + + /// <summary> + /// The default value for the byte that replaces invalid bytes in a + /// data stream when a parity error occurs is 0x3f. + /// </summary> + public const byte DEFAULT_PARITY_REPLACE = 0x3f; + + /// <summary> + /// The default value for the standard number of stopbits per byte is 1. + /// </summary> + public const StopBits DEFAULT_STOP_BITS = StopBits.One; + + /// <summary> + /// The default value for the size of the SerialPort input buffer is + /// 4096. + /// </summary> + public const int DEFAULT_READBUFFER_SIZE = 0x1000; + + /// <summary> + /// The default value for the number of milliseconds before a time-out + /// occurs when a read operation does not finish is InfiniteTimeout. + /// </summary> + public const int DEFAULT_READ_TIMEOUT = -1; + + /// <summary> + /// The default value for the size of the SerialPort output buffer is + /// 2048. + /// </summary> + public const int DEFAULT_WRITEBUFFER_SIZE = 0x800; + + /// <summary> + /// The default value for the number of milliseconds before a time-out + /// occurs when a write operation does not finish is InfiniteTimeout. + /// </summary> + public const int DEFAULT_WRITE_TIMEOUT = -1; + + /// <summary> + /// The value for InfiniteTimeout. + /// </summary> + public const int INFINITE_TIMEOUT = -1; + + #endregion + + #region Public Properties + + /// <summary> + /// Gets or sets the name of the port. + /// </summary> + //[Category(SPPConstants.Category_SerialPortSettings)] + //[Description(SPPConstants.Desc_PortName)] + public string PortName + { + get { return this.portName; } + set + { + if (this.serialPort != null) + throw new InvalidOperationException("SPPResources.Error_SP_PortSet"); + else { this.portName = value; } + } + } + + /// <summary> + /// Gets the status of the port (Opened/Closed). + /// </summary> + [Browsable(false)] + public bool IsPortOpen + { + get + { + if (this.serialPort == null) + return false; + else return this.serialPort.IsOpen; + } + } + + /// <summary> + /// Gets or sets the NetworkStream used for communicating with a remote device. + /// </summary> + [Browsable(false)] + public NetworkStream NetworkStream + { + get + { return this.networkStream; } + set + { + this.networkStream = value; + if (this.networkStream != null) + { + this.networkStream.WriteTimeout = this.readTimeout; + this.networkStream.ReadTimeout = this.writeTimeout; + } + } + } + + #region Serial Port Settings + + /// <summary> + /// Gets or sets the serial baud rate. The default value is 9600 bits + /// per second (bps). + /// </summary> + [Category("SPPConstants.Category_SerialPortSettings")] + [Description("SPPConstants.Desc_BaudRate")] + public int BaudRate + { + get + { return this.baudRate; } + set + { + if (value <= 0) + throw new ArgumentOutOfRangeException("BaudRate", + "SPPResources.Error_SP_InvalidBaudRate"); + + this.baudRate = value; + if (this.serialPort != null) + this.serialPort.BaudRate = value; + } + } + + /// <summary> + /// Gets or sets the standard length of data bits per byte. + /// The range of values for this field is from 5 through 8. + /// The default value is 8. + /// </summary> + [Category("SPPConstants.Category_SerialPortSettings")] + [Description("SPPConstants.Desc_DataBits")] + public int DataBits + { + get + { return this.dataBits; } + set + { + if ((value < MIN_DATA_BITS) || (value > MAX_DATA_BITS)) + throw new ArgumentOutOfRangeException("DataBits", + "SPPResources.Error_SP_DataBitsRange"); + + this.dataBits = value; + if (this.serialPort != null) + this.serialPort.DataBits = value; + } + } + + /// <summary> + /// Gets or sets the byte encoding for pre- and post-transmission + /// conversion of text. + /// The default is ASCIIEncoding. + /// </summary> + [Browsable(false)] + public Encoding Encoding + { + get + { return this.encoding; } + set + { + if (value == null) + this.encoding = ASCIIEncoding.ASCII; + else + { + if (((!(value is ASCIIEncoding) && + !(value is UTF8Encoding)) && + (!(value is UnicodeEncoding) && + !(value is UTF32Encoding))) && + (((value.CodePage >= 0xc350) + && (value.CodePage != 0xd698)) + || (value.GetType().Assembly != + typeof(string).Assembly))) + throw new ArgumentException( + "SPPResources.Error_SP_EncodingNotSupported", "Encoding"); + + this.encoding = value; + if (this.serialPort != null) + this.serialPort.Encoding = value; + } + } + } + + /// <summary> + /// Gets or sets the Parity-checking protocol. The default value is + /// None. + /// </summary> + //[Category(SPPConstants.Category_SerialPortSettings)] + //[Description(SPPConstants.Desc_Parity)] + public Parity Parity + { + get + { return this.parity; } + set + { + if (!Enum.IsDefined(typeof(Parity), value)) + throw new ArgumentOutOfRangeException("Parity"); + + this.parity = value; + if (this.serialPort != null) + this.serialPort.Parity = value; + } + } + + /// <summary> + /// Gets or sets the byte that replaces invalid bytes in a data stream + /// when a parity error occurs. + /// The default value is 0x3f. + /// </summary> + //[Category(SPPConstants.Category_SerialPortSettings)] + //[Description(SPPConstants.Desc_ParityReplace)] + public byte ParityReplace + { + get + { return this.parityReplace; } + set + { + this.parityReplace = value; + if (this.serialPort != null) + this.serialPort.ParityReplace = value; + } + } + + /// <summary> + /// Gets or sets the size of the SerialPort input buffer. The default + /// value is 4096. If the port is open, ReadBufferSize will not be set. + /// </summary> + //[Category(SPPConstants.Category_SerialPortSettings)] + //[Description(SPPConstants.Desc_ReadBufferSize)] + public int ReadBufferSize + { + get + { return this.readBufferSize; } + set + { + if (value <= 0) + throw new ArgumentOutOfRangeException("ReadBufferSize"); + + if (this.serialPort != null) + if (IsPortOpen) + // If the port is open, ReadBufferSize cannot be set. + // So set the portsetting values to the current port settings. + this.readBufferSize = this.serialPort.ReadBufferSize; + else + { // If the port is closed, ReadBufferSize can be set. + this.readBufferSize = value; + this.serialPort.ReadBufferSize = this.readBufferSize; + } + else this.readBufferSize = value; + } + } + + /// <summary> + /// Gets or sets the number of milliseconds before a time-out occurs + /// when a read operation does not finish. + /// InfiniteTimeout is the default value. + /// </summary> + //[Category(SPPConstants.Category_SerialPortSettings)] + //[Description(SPPConstants.Desc_ReadTimeout)] + public int ReadTimeout + { + get + { return this.readTimeout; } + set + { + if ((value < 0) && (value != -1)) + throw new ArgumentOutOfRangeException("ReadTimeout"); + + this.readTimeout = value; + if (this.serialPort != null) + this.serialPort.ReadTimeout = value; + if (networkStream != null) + networkStream.WriteTimeout = this.readTimeout; + } + } + + /// <summary> + /// Gets or sets the standard number of stopbits per byte. The default + /// value is 1. + /// </summary> + //[Category(SPPConstants.Category_SerialPortSettings)] + //[Description(SPPConstants.Desc_StopBits)] + public StopBits StopBits + { + get + { return this.stopBits; } + set + { + if (!Enum.IsDefined(typeof(StopBits), value)) + throw new ArgumentOutOfRangeException("StopBits"); + + this.stopBits = value; + if (this.serialPort != null) + this.serialPort.StopBits = value; + } + } + + /// <summary> + /// Gets or sets the size of the SerialPort output buffer. The default + /// value is 2048. If the port is open, WriteBufferSize will not be set. + /// </summary> + //[Category(SPPConstants.Category_SerialPortSettings)] + //[Description(SPPConstants.Desc_WriteBufferSize)] + public int WriteBufferSize + { + get + { return this.writeBufferSize; } + set + { + if (value <= 0) + throw new ArgumentOutOfRangeException("WriteBufferSize"); + + if (this.serialPort != null) + if (IsPortOpen) + // If the port is open, WriteBufferSize cannot be set. + // So set the portsetting values to the current port settings. + this.writeBufferSize = this.serialPort.WriteBufferSize; + else + { // If the port is closed, WriteBufferSize can be set. + this.writeBufferSize = value; + this.serialPort.WriteBufferSize = this.writeBufferSize; + } + else this.writeBufferSize = value; + } + } + + /// <summary> + /// Gets or sets the number of milliseconds before a time-out occurs + /// when a write operation does not finish. + /// InfiniteTimeout is the default value. + /// </summary> + //[Category(SPPConstants.Category_SerialPortSettings)] + //[Description(SPPConstants.Desc_WriteTimeout)] + public int WriteTimeout + { + get + { return this.writeTimeout; } + set + { + if ((value <= 0) && (value != -1)) + throw new ArgumentOutOfRangeException("WriteTimeout"); + + this.writeTimeout = value; + if (this.serialPort != null) + this.serialPort.WriteTimeout = value; + if (networkStream != null) + networkStream.ReadTimeout = this.writeTimeout; + } + } + + #endregion + + #endregion + + + public void Initialize(string id) { } + + public void Dispose() + { + //timer1.Enabled = false; + serialPort.Close(); + message("Closed connection"); + //btnConnect.Enabled = true; + //cbPorts.Enabled = true; + } + + + public BlueTooth_USB() + { + Logger = ServiceScope.Get<ILogger>(); + } + + #region IListener Member + + public void Start() + { + spp = new BluetoothSPPManager(); + spp.PortName = "COM 3"; + + spp.OpenPort(); + return; + + //GetPorts(); + + //event to handle messages recieved from the phone + //message += new phoneMessageHandler(ParseMessage); + + portName = "COM 3"; + + OpenPort(); + + + //_selectedPort = 2; + //ServiceScope.Get<IThreadPool>().Add(new DoWorkHandler(connect)); + } + + #endregion + + + + + + + + + void OpenPort() + { + if (string.IsNullOrEmpty(this.portName) || string.IsNullOrEmpty(this.portName.Trim())) + throw new InvalidOperationException("portname not set"); + + // Set up the port. + this.serialPort = new SerialPort(this.portName); + this.serialPort.DataReceived += + new SerialDataReceivedEventHandler(serialPort_DataReceived); + this.serialPort.ErrorReceived += + new SerialErrorReceivedEventHandler(serialPort_ErrorReceived); + } + + + + + + + + + + + + + + + void GetPorts() + { + //add the list of port names to select from + _ports.AddRange(SerialPort.GetPortNames()); + Logger.Debug("BlueTooth_USB: found {0} serial ports", _ports.Count); + + foreach (string port in _ports) + { + Logger.Debug("BlueTooth_USB: found serial port: {0}", port); + TestPort(port); + } + } + + + bool TestPort(string portname) + { + try + { + Logger.Debug("Bluetooth_USB: Starting TestPort for {0}.", portname); + + serialPort = new SerialPort(portname); + serialPort.Open(); + + + + Logger.Error("Bluetooth_USB: TestPort for {0} succeeded.", portname); + return true; + } + catch (Exception ex) + { + Logger.Error("Bluetooth_USB: TestPort for {0} failed.", portname); + Logger.Error(ex); + return false; + } + finally + { + serialPort.Close(); + } + } + + + + + + + void Form1_volume(string message) + { + //decode caller id + string[] sep = { "," }; + string[] volume = message.Remove(0, 6).Split(sep, StringSplitOptions.None); + + //if it is the ringer + if (volume[0].Trim() == "1") + _volumeLevel = int.Parse(volume[1]); + } + + void Form1_battery(string message) + { + //decode caller id + string[] sep = { "," }; + string[] battery = message.Remove(0, 5).Split(sep, StringSplitOptions.None); + //txtPhoneNumber.Text = caller[0]; + _powerLevel = int.Parse(battery[1]); + } + + void ParseMode(string message) + { + switch (message) + { + case "+MODE: 0": + Logger.Info("Bluetooth_USB: Using mode 0"); + _mode = 0; + break; + case "+MODE: 2": + Logger.Info("Bluetooth_USB: Using mode 2"); + _mode = 2; + break; + default: + Logger.Error("Bluetooth_USB: Unknown Mode"); + _mode = -1; + break; + } + } + + void decode_caller_id(string message) + { + + + + //decode caller id + string[] sep = { "," }; + string[] caller = message.Remove(0, 6).Split(sep, StringSplitOptions.None); + _PhoneNumber = caller[0].Remove(0, 1); + if (caller.Length > 4) + _name = caller[4]; + + + //CallAction callAction = ParseAction(strLine); + //Logger.Info(strLine); + //callAction.WriteToLog(); + + + + } + + void decode_signal_strength(string message) + { + //decode_signal_strength + switch (message) + { + case "+MSSI: 0": + + _signalStrength = 0; + Logger.Error("Bluetooth_USB: No signal found"); + break; + case "+MSSI: 1": + _signalStrength = 1; + break; + case "+MSSI: 25": + _signalStrength = 2; + break; + case "+MSSI: 56": + _signalStrength = 3; + break; + case "+MSSI: 75": + _signalStrength = 4; + break; + case "+MSSI: 90": + _signalStrength = 5; + break; + default: + Logger.Error("Bluetooth_USB: Signal strenght not recognized: " + message); + break; + } + } + + + + + private void connect() + { + SendData(ATcommand.GetManufacturer); + SendData(ATcommand.GetModel); + + + System.Threading.Thread.Sleep(5000); + + + + setMode(2); + + //get the signal strength + SendData("AT+MSSI?"); + System.Threading.Thread.Sleep(1000); + + //get the battery level + SendData("AT+CBC"); + System.Threading.Thread.Sleep(1000); + + //get the ring volumne level + SendData("AT+MAVL?"); + System.Threading.Thread.Sleep(1000); + + //set the calling line identification to enabled + SendData("AT+CLIP=1"); + System.Threading.Thread.Sleep(1000); + } + + + + + + + void port_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) + { + //error = _currentPort.ReadExisting(); + //this.Invoke(new EventHandler(SetErrorText)); + } + + + + + + + + void port_DataReceived(object sender, SerialDataReceivedEventArgs e) + { + //displayString = _currentPort.ReadExisting(); + //this.Invoke(new EventHandler(DisplayReceiveData)); + Logger.Debug("Bluetooth_USB: ATcommand: {0}", serialPort.ReadExisting()); + + return; + + string buffer = ReadBuffer(); + + switch (buffer) + { + case ATcommand.GetManufacturer: + { + Logger.Debug("Bluetooth_USB: mobile phone manufacturer: {0}", ReadBuffer()); + Logger.Debug("Bluetooth_USB: mobile phone result: {0}", ReadBuffer()); + break; + } + case ATcommand.GetModel: + { + Logger.Debug("Bluetooth_USB: mobile phone model: {0}", ReadBuffer()); + Logger.Debug("Bluetooth_USB: mobile phone result: {0}", ReadBuffer()); + break; + } + default: + Logger.Debug("Bluetooth_USB: Unknown ATcommand: {0}", buffer); + break; + } + + + + + } + + + + + + void ParseMessage(string message) + { + if (message.Length < 1) return; + Logger.Debug("Bluetooth_USB: received DATA: {0}", message); + + //signal strength + if (message.StartsWith("+MSSI")) + { + signalStrengthHandler s = new signalStrengthHandler(decode_signal_strength); + //this.Invoke(s, new object[] { message }); + return; + } + + //Caller ID + if (message.StartsWith("+CLIP")) + { + callerIdHandler c = new callerIdHandler(decode_caller_id); + //this.Invoke(c, new object[] { message }); + return; + } + + //mode + if (message.StartsWith("+MODE")) + { + modeHandler m = new modeHandler(ParseMode); + //this.Invoke(m, new object[] { message }); + return; + } + + //battery status + if (message.StartsWith("+CBC")) + { + batteryStatusHandler b = new batteryStatusHandler(Form1_battery); + //this.Invoke(b, new object[] { message }); + return; + } + + //volume level + if (message.StartsWith("+MAVL")) + { + volumeHandler v = new volumeHandler(Form1_volume); + //this.Invoke(v, new object[] { message }); + //return; + } + } + + + + + + + + string ReadBuffer() + { + Logger.Debug("ReadBuffer"); + //Logger.Debug(strBuffer); + + + ////this does not work, because i am not able to remove the \n at the end + //string strBuffer = _currentPort.ReadLine(); + //if (cToRem == char.MinValue) + // cToRem = strBuffer[strBuffer.Length - 1]; + //strBuffer.Trim(cToRem); + //Logger.Debug(strBuffer); + //return strBuffer; + + + int buffersize = serialPort.BytesToRead; + StringBuilder line = new StringBuilder(); + int Bval; + for (int i = 0; i < buffersize; i++) + { + //data is received read the message + Bval = serialPort.ReadByte(); + switch (Bval) + { + case 10: //new line + return line.ToString(); + break; + case 13: //carriage return - ignore + break; + default: //build string message + line.Append(char.ConvertFromUtf32(Bval)); + break; + } + } + return line.ToString(); + + + //Logger.Debug(strBuffer); + + //int buffersize = _currentPort.BytesToRead; + //StringBuilder line = new StringBuilder(); + //int Bval; + //for (int i = 0; i < buffersize; i++) + //{ + // //data is received read the message + // Bval = _currentPort.ReadByte(); + // Logger.Debug("alter string '{0}' ::: neues byte '{1}' zeichen '{2}'", line.ToString(), Bval, char.ConvertFromUtf32(Bval)); + // switch (Bval) + // { + // case 10: //new line + // message(line.ToString()); + // line = new StringBuilder(); + // break; + // case 13: //carriage return - ignore + // break; + // default: //build string message + // line.Append(char.ConvertFromUtf32(Bval)); + // break; + // } + //} + ////send string message for processing. + //message(line.ToString()); + } + + void SendData(string value) + { + Logger.Debug("Bluetooth_USB: Data SEND: {0}", value); + + //convert the string data to + //byte values to send to the phone + StringBuilder sb = new StringBuilder(value); + int size = sb.Length; + byte[] data = new byte[size + 1]; + for (int i = 0; i < sb.Length; i++) + { + data[i] = (byte)sb[i]; + } + data[size] = (byte)Convert.ToChar(13); + + //send the data + if (serialPort.IsOpen) + serialPort.Write(data, 0, size + 1); + else + { + //timer1.Enabled = false; + Logger.Error("Bluetooth port not opend"); + message("Port not opened"); + } + System.Threading.Thread.Sleep(1000); + } + + + + + private void timer1_Tick(object sender, EventArgs e) + { + //request cellular signal strength + SendData("AT+MSSI?"); + } + + private void checkSignal() + { + //enable the timer which checks + //the signal strength every two minutes. + //timer1.Enabled = true; + + //set the mode to 2 + setMode(2); + + //get the signal strength + SendData("AT+MSSI?"); + System.Threading.Thread.Sleep(1000); + + //get the battery level + SendData("AT+CBC"); + System.Threading.Thread.Sleep(1000); + + //get the ring volumne level + SendData("AT+MAVL?"); + } + + private void volumeLevel_Scroll(object sender, EventArgs e) + { + setMode(2); + SendData("AT+MAVL=1," + _volumeLevel.ToString()); + } + + + + + #region Private Functions/Methods + + /// <summary> + /// Sets up the serial port. + /// </summary> + /// <exception cref="InvalidOperationException">PortName is not set.</exception> + private void SetupSerialPort() + { + if (string.IsNullOrEmpty(this.portName) || string.IsNullOrEmpty(this.portName.Trim())) + throw new InvalidOperationException("portname not set"); + + // Set up the port. + this.serialPort = new SerialPort(this.portName); + this.serialPort.DataReceived += + new SerialDataReceivedEventHandler(serialPort_DataReceived); + this.serialPort.ErrorReceived += + new SerialErrorReceivedEventHandler(serialPort_ErrorReceived); + + // Configure the port. + ConfigurePort(); + } + + /// <summary> + /// Configures the serial port settings. + /// Note that ReadBufferSize and WriteBufferSize will not be set if the + /// port is open. + /// </summary> + /// <exception cref="ArgumentNullException">PortSettings property has + /// not been set.</exception> + private void ConfigurePort() + { + serialPort.BaudRate = this.baudRate; + serialPort.DataBits = this.dataBits; + if (this.encoding != null) + serialPort.Encoding = this.encoding; + serialPort.Parity = this.parity; + serialPort.ParityReplace = this.parityReplace; + serialPort.StopBits = this.stopBits; + serialPort.ReadTimeout = this.readTimeout; + if (networkStream != null) + { + networkStream.WriteTimeout = this.readTimeout; + networkStream.ReadTimeout = this.writeTimeout; + } + serialPort.WriteTimeout = this.writeTimeout; + + if (IsPortOpen) + { + // If the port is open, ReadBufferSize and WriteBufferSize + // cannot be set. So set the portsetting values to the + // current port settings. + this.readBufferSize = serialPort.ReadBufferSize; + this.writeBufferSize = serialPort.WriteBufferSize; + } + else + { + // If the port is closed, ReadBufferSize and WriteBufferSize + // can be set. + serialPort.ReadBufferSize = this.readBufferSize; + serialPort.WriteBufferSize = this.writeBufferSize; + } + } + + /// <summary> + /// Helps the serialCommEventThread to listen to the NetworkStream. + /// If data is available, it raises a DataDetectedFromRemoteDevice + /// event. + /// </summary> + private void ReceiveThread() + { + while (this.IsPortOpen) + { + Thread.Sleep(100); + // Raise an event that data is detected on the Network stream. + if (this.networkStream.DataAvailable) + if (DataDetectedFromRemoteDevice != null) + DataDetectedFromRemoteDevice(this, new EventArgs()); + } + } + + /// <summary> + /// This is the handler method for the serial port when an error is + /// received on the port. It raises an ErrorReceived event. + /// </summary> + /// <param name="sender">The sender of the event.</param> + /// <param name="e">Provides data for the serial port's ErrorReceived + /// event.</param> + private void serialPort_ErrorReceived( + object sender, SerialErrorReceivedEventArgs e) + { + string errorMessage = string.Empty; + switch (e.EventType) + { + case SerialError.Frame: + errorMessage = "SPPResources.Error_SP_Frame"; + break; + + case SerialError.Overrun: + errorMessage = "SPPResources.Error_SP_Overrun"; + break; + + case SerialError.RXOver: + errorMessage = "SPPResources.Error_SP_RXOver"; + break; + + case SerialError.RXParity: + errorMessage = "SPPResources.Error_SP_RXParity"; + break; + + case SerialError.TXFull: + errorMessage = "SPPResources.Error_SP_TXFull"; + break; + } + throw new SPPException( + SerialCommErrorType.SerialPortError, errorMessage); + } + + /// <summary> + /// This is the handler method for the serial port when data is received + /// on the port. It raises a DataDetectedOnSerialPort event. + /// </summary> + /// <param name="sender">The sender of the event.</param> + /// <param name="e">Provides data for the serial port's DataReceived + /// event.</param> + private void serialPort_DataReceived( + object sender, SerialDataReceivedEventArgs e) + { + // Since data is detected on the serial port, raise an event. + if (DataDetectedOnSerialPort != null) + DataDetectedOnSerialPort(sender, new EventArgs()); + } + + #endregion + + + #region Commands + + + private void setMode(int val) + { + if (_mode == val) + return; + switch (val) + { + case 0: + //set the mode to 0 + SendData("AT+MODE=0"); + break; + + case 2: + //set the mode to 2 + SendData("AT+MODE=2"); + break; + default: + Logger.Error("Mode: " + val.ToString() + " not recognized."); + break; + } + System.Threading.Thread.Sleep(1000); + SendData("AT+MODE?"); + } + + #endregion + + } +} Added: trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/BlueTooth_USB.csproj =================================================================== --- trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/BlueTooth_USB.csproj (rev 0) +++ trunk/plugins/FritzBox/MP2version/Listeners/BlueTooth_USB/BlueTooth_USB.csproj 2008-02-16 15:46:56 UTC (rev 1372) @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>8.0.50727</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{501A8A8C-E843-44C8-B680-656E06F99F17}</ProjectGuid> + <OutputType>Library</OutputType> + <AppDesignerFolder>Properties</AppDesignerFolder> + <RootNamespace>CallMonitor.Listeners</RootNamespace> + <AssemblyName>BlueTooth_USB</AssemblyName> + <StartupObject> + </StartupObject> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <Optimize>false</Optimize> + <OutputPath>bin\x86\Debug\</OutputPath> + <DefineConstants>DEBUG;TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <PlatformTarget>x86</PlatformTarget> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <Optimize>true</Optimize> + <OutputPath>bin\x86\Release\</OutputPath> + <DefineConstants>TRACE</DefineConstants> + <ErrorReport>prompt</ErrorReport> + <WarningLevel>4</WarningLevel> + <PlatformTarget>x86</PlatformTarget> + </Prop... [truncated message content] |