Server/CecClient.cs
author StephaneLenclud
Mon, 29 Aug 2016 17:36:02 +0200
changeset 256 51b86efdc448
parent 214 4961ede27e0a
permissions -rw-r--r--
Published V.1.0.5.
Providing Harmony Hub reconnect.
     1 /*
     2  * This file is part of the libCEC(R) library.
     3  *
     4  * libCEC(R) is Copyright (C) 2011-2013 Pulse-Eight Limited.    All rights reserved.
     5  * libCEC(R) is an original work, containing original code.
     6  *
     7  * libCEC(R) is a trademark of Pulse-Eight Limited.
     8  *
     9  * This program is dual-licensed; you can redistribute it and/or modify
    10  * it under the terms of the GNU General Public License as published by
    11  * the Free Software Foundation; either version 2 of the License, or
    12  * (at your option) any later version.
    13  *
    14  * This program is distributed in the hope that it will be useful,
    15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.    See the
    17  * GNU General Public License for more details.
    18  *
    19  * You should have received a copy of the GNU General Public License
    20  * along with this program; if not, write to the Free Software
    21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
    22  *
    23  *
    24  * Alternatively, you can license this library under a commercial license,
    25  * please contact Pulse-Eight Licensing for more information.
    26  *
    27  * For more information contact:
    28  * Pulse-Eight Licensing             <license@pulse-eight.com>
    29  *         http://www.pulse-eight.com/
    30  *         http://www.pulse-eight.net/
    31  */
    32 
    33 using System;
    34 using System.Text;
    35 using CecSharp;
    36 using System.Threading;
    37 using System.Diagnostics;
    38 
    39 namespace Cec
    40 {
    41     class Client : CecCallbackMethods
    42     {
    43         /// <summary>
    44         /// Enable public static access
    45         /// </summary>
    46         public static Client Static;
    47 
    48         /// <summary>
    49         /// Provide direct access to CEC library
    50         /// </summary>
    51         public LibCecSharp Lib
    52         {
    53             get
    54             {
    55                 return iLib;
    56             }
    57         }
    58 
    59         /// <summary>
    60         /// 
    61         /// </summary>
    62         public int LogLevel = (int)CecLogLevel.Notice;
    63 
    64         /// <summary>
    65         /// 
    66         /// </summary>
    67         public bool FilterOutPollLogs = true;
    68 
    69         /// <summary>
    70         /// 
    71         /// </summary>
    72         private LibCecSharp iLib;
    73         /// <summary>
    74         /// 
    75         /// </summary>
    76         private LibCECConfiguration Config;
    77 
    78         /// <summary>
    79         /// 
    80         /// </summary>
    81         private bool iConnected;
    82 
    83         /// <summary>
    84         /// 
    85         /// </summary>
    86         /// <param name="aDeviceName"></param>
    87         /// <param name="aHdmiPort"></param>
    88         public Client(string aDeviceName, byte aHdmiPort, CecDeviceType aDeviceType = CecDeviceType.PlaybackDevice)
    89         {
    90             Config = new LibCECConfiguration();
    91             Config.DeviceTypes.Types[0] = aDeviceType;
    92             Config.DeviceName = aDeviceName;
    93             Config.HDMIPort = aHdmiPort;
    94             //Config.ClientVersion = LibCECConfiguration.CurrentVersion;
    95             Config.SetCallbacks(this);
    96 
    97             iLib = new LibCecSharp(Config);
    98             iLib.InitVideoStandalone();
    99 
   100             if (Static != null)
   101             {
   102                 Trace.WriteLine("WARNING: CEC client static already exists");
   103             }
   104             else
   105             {
   106                 Static = this;
   107             }
   108             
   109 
   110             //Trace.WriteLine("CEC Parser created - libCEC version " + Lib.VersionToString(Config.ServerVersion));
   111             Trace.WriteLine("INFO: CEC Parser created - libCEC version " + Config.ServerVersion);
   112         }
   113 
   114 
   115         /// <summary>
   116         /// 
   117         /// </summary>
   118         /// <param name="alert"></param>
   119         /// <param name="data"></param>
   120         /// <returns></returns>
   121         public override int ReceiveAlert(CecAlert alert, CecParameter data)
   122         {
   123             string log = "CEC alert: " + alert.ToString();
   124             if (data != null && data.Type == CecParameterType.ParameterTypeString)
   125             {
   126                 log += " " + data.Data;
   127             }
   128 
   129             Trace.WriteLine(log);
   130 
   131             Close();
   132             //Try reconnect
   133             Open(1000);
   134             return 1;
   135         }
   136 
   137         /// <summary>
   138         /// 
   139         /// </summary>
   140         /// <param name="newVal"></param>
   141         /// <returns></returns>
   142         public override int ReceiveMenuStateChange(CecMenuState newVal)
   143         {
   144             Trace.WriteLine("CEC menu state changed to: " + iLib.ToString(newVal));
   145             return 1;
   146         }
   147 
   148         /// <summary>
   149         /// 
   150         /// </summary>
   151         /// <param name="logicalAddress"></param>
   152         /// <param name="activated"></param>
   153         public override void SourceActivated(CecLogicalAddress logicalAddress, bool activated)
   154         {
   155             Trace.WriteLine("CEC source activated: " + iLib.ToString(logicalAddress) + "/" + activated.ToString() );
   156             return;
   157         }
   158 
   159         public override int ReceiveCommand(CecCommand command)
   160         {
   161             Trace.WriteLine(string.Format("CEC command '{5}' from {0} to {1} - Ack: {2} Eom: {3} OpcodeSet: {4} Timeout: {6}",
   162                 iLib.ToString(command.Initiator),
   163                 iLib.ToString(command.Destination),
   164                 command.Ack.ToString(),
   165                 command.Eom.ToString(),
   166                 command.OpcodeSet.ToString(),
   167                 iLib.ToString(command.Opcode),
   168                 command.TransmitTimeout.ToString()
   169                 ));
   170             return 1;
   171         }
   172 
   173         public override int ReceiveKeypress(CecKeypress key)
   174         {
   175             Trace.WriteLine(string.Format("CEC keypress: {0} Duration:{1} Empty: {2}",
   176                 key.Keycode.ToString(), key.Duration.ToString(), key.Empty.ToString()));
   177             return 1;
   178         }
   179 
   180         public override int ReceiveLogMessage(CecLogMessage message)
   181         {
   182             if (((int)message.Level & LogLevel) == (int)message.Level)
   183             {
   184                 string strLevel = "";
   185                 switch (message.Level)
   186                 {
   187                     case CecLogLevel.Error:
   188                         strLevel = "ERROR: ";
   189                         break;
   190                     case CecLogLevel.Warning:
   191                         strLevel = "WARNING: ";
   192                         break;
   193                     case CecLogLevel.Notice:
   194                         strLevel = "NOTICE: ";
   195                         break;
   196                     case CecLogLevel.Traffic:
   197                         strLevel = "TRAFFIC: ";
   198                         break;
   199                     case CecLogLevel.Debug:
   200                         strLevel = "DEBUG: ";
   201                         if (message.Message.IndexOf("POLL") != -1 && FilterOutPollLogs)
   202                         {
   203                             //We have an option to prevent spamming with poll debug logs
   204                             return 1;
   205                         }
   206                         break;
   207                     default:
   208                         break;
   209                 }
   210                 string strLog = string.Format("{0} {1} {2}", strLevel, message.Time, message.Message);
   211                 Trace.WriteLine(strLog);
   212                 
   213             }
   214             return 1;
   215         }
   216 
   217         /// <summary>
   218         /// 
   219         /// </summary>
   220         /// <param name="timeout"></param>
   221         /// <returns></returns>
   222         public bool Open(int timeout)
   223         {
   224             Close();         
   225             CecAdapter[] adapters = iLib.FindAdapters(string.Empty);
   226             if (adapters.Length > 0)
   227             {
   228                 Open(adapters[0].ComPort, timeout);                
   229             }                
   230             else
   231             {
   232                 Trace.WriteLine("CEC did not find any adapters");
   233             }
   234 
   235             return iConnected;
   236         }
   237 
   238         public bool Open(string port, int timeout)
   239         {
   240             Close();
   241             iConnected = iLib.Open(port, timeout);
   242             return iConnected;
   243         }
   244 
   245         public void Close()
   246         {            
   247             iLib.Close();
   248             iConnected = false;
   249         }
   250 
   251 
   252         public void TestSendKey()
   253         {
   254             //SetupMenu: opens option menu
   255             //RootMenu: opens Android home menu
   256             //ContentsMenu: nop
   257             //FavoriteMenu: nop
   258 
   259             //Philips TopMenu = 16
   260             //Philips PopupMenu = 17
   261 
   262             //bool res = iLib.SendKeypress(CecLogicalAddress.Tv, CecUserControlCode.DisplayInformation, true);
   263             //Thread.Sleep(3000); //Wait few seconds for menu to open
   264                                 //res = iLib.SendKeypress(CecLogicalAddress.Tv, CecUserControlCode.SetupMenu, true);
   265 
   266             for (int i = 0; i < 256; i++)
   267             {
   268                 //Thread.Sleep(100);
   269                 //res = iLib.SendKeyRelease(CecLogicalAddress.Tv, true);
   270                 //Thread.Sleep(100);
   271                 switch ((CecUserControlCode)i)
   272                 {
   273                     case CecUserControlCode.Power:
   274                     case CecUserControlCode.PowerOffFunction:
   275                     case CecUserControlCode.PowerOnFunction:
   276                     case CecUserControlCode.PowerToggleFunction:
   277                     case CecUserControlCode.ElectronicProgramGuide:
   278                     case CecUserControlCode.InputSelect:
   279                     case CecUserControlCode.RootMenu:
   280 
   281                         break;
   282 
   283                     default:
   284                         Trace.WriteLine(i.ToString());
   285                         Thread.Sleep(1000);
   286                         iLib.SendKeypress(CecLogicalAddress.Tv, (CecUserControlCode)i, true);
   287                         
   288                         break;
   289 
   290                 }
   291                 
   292                 //
   293             }
   294 
   295 
   296             for (int i=0;i<7;i++)
   297             {
   298                 //Thread.Sleep(100);
   299                 //res = iLib.SendKeyRelease(CecLogicalAddress.Tv, true);
   300                 //Thread.Sleep(100);
   301                 //res = iLib.SendKeypress(CecLogicalAddress.Tv, CecUserControlCode.Down, true);
   302                 //
   303             }
   304 
   305             //res = iLib.SendKeypress(CecLogicalAddress.Tv, CecUserControlCode.Select, true);
   306 
   307             //res = iLib.SendKeypress(CecLogicalAddress.Tv, CecUserControlCode.Select, true);
   308             //res = iLib.SendKeyRelease(CecLogicalAddress.Tv, true);
   309         }
   310 
   311         /// <summary>
   312         /// 
   313         /// </summary>
   314         public void Scan()
   315         {
   316             string scanRes = "";
   317             scanRes += "CEC bus information\n";
   318             scanRes += "===================\n";
   319             CecLogicalAddresses addresses = Lib.GetActiveDevices();
   320             for (int iPtr = 0; iPtr < addresses.Addresses.Length; iPtr++)
   321             {
   322                 CecLogicalAddress address = (CecLogicalAddress) iPtr;
   323                 if (!addresses.IsSet(address))
   324                     continue;
   325 
   326                 CecVendorId iVendorId = Lib.GetDeviceVendorId(address);
   327                 bool bActive = Lib.IsActiveDevice(address);
   328                 ushort iPhysicalAddress = Lib.GetDevicePhysicalAddress(address);
   329                 string strAddr = Lib.PhysicalAddressToString(iPhysicalAddress);
   330                 CecVersion iCecVersion = Lib.GetDeviceCecVersion(address);
   331                 CecPowerStatus power = Lib.GetDevicePowerStatus(address);
   332                 string osdName = Lib.GetDeviceOSDName(address);
   333                 string lang = Lib.GetDeviceMenuLanguage(address);
   334 
   335                 scanRes += "device #" + iPtr + ": " + Lib.ToString(address) + "\n";
   336                 scanRes += "address:       " + strAddr + "\n";
   337                 scanRes += "active source: " + (bActive ? "yes" : "no") + "\n";
   338                 scanRes += "vendor:        " + Lib.ToString(iVendorId) + "\n";
   339                 scanRes += "osd string:    " + osdName + "\n";
   340                 scanRes += "CEC version:   " + Lib.ToString(iCecVersion) + "\n";
   341                 scanRes += "power status:  " + Lib.ToString(power) + "\n";
   342                 if (!string.IsNullOrEmpty(lang))
   343                     scanRes += "language:      " + lang + "\n";
   344                 scanRes += "===================" + "\n";
   345             }
   346 
   347             Trace.Write(scanRes);
   348         }
   349 
   350         public void ListAdapters()
   351         {
   352             int iAdapter = 0;
   353             foreach (CecAdapter adapter in iLib.FindAdapters(string.Empty))
   354             {
   355                 Trace.WriteLine("Adapter:    " + iAdapter++);
   356                 Trace.WriteLine("Path:         " + adapter.Path);
   357                 Trace.WriteLine("Com port: " + adapter.ComPort);
   358             }
   359         }
   360        
   361 
   362     }
   363 }