Esempio n. 1
0
 /// <summary>
 /// Creates the new channel.
 /// </summary>
 /// <param name="channel">The high level tuning detail.</param>
 /// <param name="info">The subchannel detail.</param>
 /// <returns>The new channel.</returns>
 protected override IChannel CreateNewChannel(IChannel channel, ChannelInfo info)
 {
   DVBSChannel tuningChannel = (DVBSChannel)channel;
   DVBSChannel dvbsChannel = new DVBSChannel();
   dvbsChannel.Name = info.service_name;
   dvbsChannel.LogicalChannelNumber = info.LCN;
   dvbsChannel.Provider = info.service_provider_name;
   dvbsChannel.SymbolRate = tuningChannel.SymbolRate;
   dvbsChannel.Polarisation = tuningChannel.Polarisation;
   dvbsChannel.SwitchingFrequency = tuningChannel.SwitchingFrequency;
   dvbsChannel.Frequency = tuningChannel.Frequency;
   dvbsChannel.IsTv = IsTvService(info.serviceType);
   dvbsChannel.IsRadio = IsRadioService(info.serviceType);
   dvbsChannel.NetworkId = info.networkID;
   dvbsChannel.ServiceId = info.serviceID;
   dvbsChannel.TransportId = info.transportStreamID;
   dvbsChannel.PmtPid = info.network_pmt_PID;
   dvbsChannel.DisEqc = tuningChannel.DisEqc;
   dvbsChannel.BandType = tuningChannel.BandType;
   dvbsChannel.FreeToAir = !info.scrambled;
   dvbsChannel.SatelliteIndex = tuningChannel.SatelliteIndex;
   dvbsChannel.ModulationType = tuningChannel.ModulationType;
   dvbsChannel.InnerFecRate = tuningChannel.InnerFecRate;
   dvbsChannel.Pilot = tuningChannel.Pilot;
   dvbsChannel.Rolloff = tuningChannel.Rolloff;
   Log.Log.Write("Found: {0}", dvbsChannel);
   return dvbsChannel;
 }
Esempio n. 2
0
        /// <summary>
        /// Determines whether the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>.
        /// </summary>
        /// <param name="obj">The <see cref="T:System.Object"></see> to compare with the current <see cref="T:System.Object"></see>.</param>
        /// <returns>
        /// true if the specified <see cref="T:System.Object"></see> is equal to the current <see cref="T:System.Object"></see>; otherwise, false.
        /// </returns>
        public override bool Equals(object obj)
        {
            if ((obj as DVBSChannel) == null)
            {
                return(false);
            }
            if (!base.Equals(obj))
            {
                return(false);
            }
            DVBSChannel ch = obj as DVBSChannel;

            if (ch.Polarisation != Polarisation)
            {
                return(false);
            }
            if (ch.SatelliteIndex != SatelliteIndex)
            {
                return(false);
            }
            if (ch.SymbolRate != SymbolRate)
            {
                return(false);
            }
            if (ch.SwitchingFrequency != SwitchingFrequency)
            {
                return(false);
            }
            if (ch.DisEqc != DisEqc)
            {
                return(false);
            }
            if (ch.BandType != BandType)
            {
                return(false);
            }
            if (ch.ModulationType != ModulationType)
            {
                return(false);
            }
            if (ch.InnerFecRate != InnerFecRate)
            {
                return(false);
            }
            if (ch.Pilot != Pilot)
            {
                return(false);
            }
            if (ch.Rolloff != Rolloff)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 3
0
        /// <summary>
        /// Determins if the tuning paramter is HiBand and if so involke the 22Khz switch.
        /// </summary>
        /// <param name="channel">tuning details for specific channel / frequency</param>
        /// <param name="parameters">holds the parameters needed for tuning channel </param>
        /// <returns></returns>
        public static bool IsHiBand(DVBSChannel channel, ScanParameters parameters)
        {
            int lof1, lof2, sw;

            GetDefaultLnbSetup(parameters, channel.BandType, out lof1, out lof2, out sw);

            if (sw == 0)
            {
                return(false);
            }
            return(channel.Frequency >= (sw * 1000));
        }
Esempio n. 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DVBSChannel"/> class.
 /// </summary>
 /// <param name="chan">The chan.</param>
 public DVBSChannel(DVBSChannel chan)
     : base(chan)
 {
     _polarisation       = chan.Polarisation;
     _symbolRate         = chan.SymbolRate;
     _switchingFrequency = chan.SwitchingFrequency;
     DisEqc          = chan.DisEqc;
     _bandType       = chan.BandType;
     _modulation     = chan.ModulationType;
     _innerFecRate   = chan.InnerFecRate;
     _pilot          = chan.Pilot;
     _rollOff        = chan.Rolloff;
     _satelliteIndex = chan.SatelliteIndex;
 }
Esempio n. 5
0
        /// <summary>
        /// Checks if the given channel and this instance are on the different transponder
        /// </summary>
        /// <param name="channel">Channel to check</param>
        /// <returns>true, if the channels are on the same transponder</returns>
        public override bool IsDifferentTransponder(IChannel channel)
        {
            DVBSChannel dvbsChannel = channel as DVBSChannel;

            if (dvbsChannel == null)
            {
                return(true);
            }
            return(dvbsChannel.Frequency != Frequency ||
                   dvbsChannel.Polarisation != Polarisation ||
                   dvbsChannel.ModulationType != ModulationType ||
                   dvbsChannel.SatelliteIndex != SatelliteIndex ||
                   dvbsChannel.InnerFecRate != InnerFecRate ||
                   dvbsChannel.Pilot != Pilot ||
                   dvbsChannel.Rolloff != Rolloff ||
                   dvbsChannel.DisEqc != DisEqc);
        }
Esempio n. 6
0
        /// <summary>
        /// Gets the Antenna Number (or LNB number)
        /// </summary>
        /// <param name="channel">holds tuning details for DVB-S</param>
        /// <returns></returns>
        public static int GetAntennaNr(DVBSChannel channel)
        {
            byte disEqcPort = 0;

            switch (channel.DisEqc)
            {
            case DisEqcType.None:
                disEqcPort = 0; //no diseqc
                break;

            case DisEqcType.SimpleA: //simple A
                disEqcPort = 1;
                break;

            case DisEqcType.SimpleB: //simple B
                disEqcPort = 2;
                break;

            case DisEqcType.Level1AA: //Level 1 A/A
                disEqcPort = 1;
                break;

            case DisEqcType.Level1AB: //Level 1 A/B
                disEqcPort = 2;
                break;

            case DisEqcType.Level1BA: //Level 1 B/A
                disEqcPort = 3;
                break;

            case DisEqcType.Level1BB: //Level 1 B/B
                disEqcPort = 4;
                break;
            }
            return(disEqcPort);
        }
        public bool Importxmlfile(string filename)
        {
            XmlDocument doc = new XmlDocument();
            POSTIMPORT = "";
            if (DEBUG == true)
                textoutput("BackupSettings: Trying to import channels from " + filename);
            try
            {
                doc.Load(filename);
            }
            catch (Exception exc)
            {
                textoutput("<RED>Could not load xml file " + filename);
                if (DEBUG == true)
                    textoutput("<RED>Exception message is:" + exc.Message);

                return (false);
            }

            //list all cards and initiate translationtable

            #if(MP100)
            IList allTVcards = Card.ListAll();
            #elif (MP101)
            IList<Card> allTVcards = Card.ListAll();
            #else //MP11BETA or SVN
            IList<Card> allTVcards = Card.ListAll();
            #endif

            bool[] TVcardassigned = new bool[allTVcards.Count + 1];
            Card[] TVcards = new Card[allTVcards.Count + 1];

            //count all cards in xml file
            XmlNodeList cardList = doc.SelectNodes("/tvserver/servers/server/cards/card");
            Int32 xmlcardnumbers = cardList.Count;
            Int32[] cardidpos = new Int32[xmlcardnumbers + 1];
            int i = 1;
            foreach (XmlNode nodecard in cardList)
            {
                int cardid = Convert.ToInt32(nodecard.Attributes["IdCard"].Value);
                cardidpos[i] = cardid;
                i++;
            }

            int allXMLcards = i - 1;
            bool[] xmlcardassigned = new bool[allXMLcards + 1];
            int[] cardmaptranslator = new int[allXMLcards + 1];
            //initialize tv card TVcardassigned
            i = 1;

            foreach (Card dbservercard in allTVcards)
            {
                TVcards[i] = dbservercard;
                TVcardassigned[i] = false;

                i++;
            }

            //initialize cardmaptranslator and xmlcardsassigned
            for (i = 0; i <= allXMLcards; i++)
            {
                cardmaptranslator[i] = 0;
                xmlcardassigned[i] = false;
            }

            // check if plugins are available

            bool ok = plugincheck();
            if (ok == false)
                return false;

            try
            {

                CountryCollection collection = new CountryCollection();
                TvBusinessLayer layer = new TvBusinessLayer();

                bool identicalCards = false;
                int motorCount = 0;
                int serverCount = 0;
                int cardCount = 0;
                int channelCount = 0;
                int programCount = 0;
                int scheduleCount = 0;
                int recordingCount = 0;
                int channelGroupCount = 0;
                int radiochannelGroupCount = 0;
                int tvmovieCount = 0;

                // version check

                XmlNodeList versionList = doc.SelectNodes("/tvserver/versions/pluginversion");
                bool versionfound = false;
                foreach (XmlNode nodeversion in versionList)
                {
                    string restoreversion;
                    versionfound = true;
                    try
                    {
                        restoreversion = nodeversion.Attributes["backupSettingVersion"].Value;
                    }
                    catch
                    {
                        restoreversion = "0.0.0.1";
                    }

                    string actualversion = detectplugin("BackupSettings");
                    if (restoreversion != actualversion)
                    {
                        textoutput("<YELLOW>Warning: actual BackupSetting plugin version is " + actualversion);
                        textoutput("<YELLOW>Backup data were created by version " + restoreversion);
                        try
                        {
                            myMessageBox("Backup data were created with an older version of BackupSettings\nIn case of problems install the older plugin version from\n" + filename.Substring(0, filename.Length - 22) + @"TV_Program\Plugins", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                        }
                        catch (Exception exc)
                        {
                            if (DEBUG == true)
                            {
                                textoutput("<RED>MessageBox Exception is " + exc.Message);
                            }
                            return false;
                        }

                    }
                }
                if (versionfound == false)
                {
                    textoutput("<YELLOW>No version number found - backup data were created by version 0.0.0.1 or 0.0.0.2");
                }

                // Delete Channels

                if (delete_channels == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_DeleteAllChannels);
                    textoutput("Deleting all channels - Please be patient");

                    channelCount = 0;

                    try
                    {
                        foreach (Channel tmpChannel in Channel.ListAll())
                        {
                            try
                            {
                                tmpChannel.Delete();
                                channelCount++;
                            }
                            catch
                            {
                                textoutput("<RED>Channel " + tmpChannel.DisplayName + " number " + channelCount.ToString() + " could not be deleted");
                            }
                        }
                    }
                    catch
                    {
                        textoutput("<YELLOW>Channels could not be listed");
                    }

                    textoutput(channelCount + " Channels deleted");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_DeleteAllChannels);
                }

                // Delete Schedules and Programs
                if (delete_schedules == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_deleteAllSchedules);
                    textoutput("Deleting all programs from database");

                    programCount = 0;
            #if(MP100)
                    IList programs = Program.ListAll();
            #elif(MP101)
                    IList<Program> programs = Program.ListAll();
            #else //MP11BETA or SVN
                    IList<Program> programs = Program.ListAll();
            #endif

                    foreach (Program tmpProgram in programs)
                    {
                        tmpProgram.Delete();
                        programCount++;
                    }

                    textoutput(programCount + " Programs deleted");
                    // end program delete

                    //schedules
                    textoutput("Deleting all schedules from database");

                    scheduleCount = 0;
            #if(MP100)
                    IList schedules = Schedule.ListAll();
            #elif(MP101)
                    IList<Schedule> allschedules = Schedule.ListAll();
            #else //MP11BETA or SVN
                    IList<Schedule> allschedules = Schedule.ListAll();
            #endif

                    foreach (Schedule tmpSchedule in allschedules)
                    {
                        tmpSchedule.Delete();
                        scheduleCount++;
                    }

                    textoutput(scheduleCount + " Schedules deleted");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_deleteAllSchedules);
                }

                // Delete Recordings
                if (delete_recordings == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_DeleteAllRecordings);
                    textoutput("Deleting all recordings from database");

                    recordingCount = 0;
            #if(MP100)
                    IList allrecordings = Recording.ListAll();
            #elif(MP101)
                    IList<Recording> allrecordings = Recording.ListAll();
            #else //MP11BETA or SVN
                    IList<Recording> allrecordings = Recording.ListAll();
            #endif

                    foreach (Recording tmpRecording in allrecordings)
                    {
                        tmpRecording.Delete();
                        recordingCount++;
                    }

                    textoutput(recordingCount + " Recordings deleted from database");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_DeleteAllRecordings);

                }

                // Delete Channel groups
                if (delete_tvgroups == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_DeleteAllTvGroups);
                    textoutput("Deleting all TV groups");

                    channelGroupCount = 0;
            #if(MP100)
                    IList tvgroups = ChannelGroup.ListAll();
            #elif(MP101)
                    IList<ChannelGroup> alltvgroups = ChannelGroup.ListAll();
            #else //MP11BETA or SVN
                    IList<ChannelGroup> alltvgroups = ChannelGroup.ListAll();
            #endif

                    foreach (ChannelGroup tmpGroup in alltvgroups)
                    {
                        tmpGroup.Delete();
                        channelGroupCount++;
                    }

                    textoutput(channelGroupCount + " TV groups deleted");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_DeleteAllTvGroups);

                }

                // Delete Radio Channel Groups
                if (delete_radiogroups == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_DeleteAllRadioGroups);
                    textoutput("Deleting all radio groups");

                    radiochannelGroupCount = 0;
            #if(MP100)
                    IList allradiogroups = RadioChannelGroup.ListAll();
            #elif(MP101)
                    IList<RadioChannelGroup> allradiogroups = RadioChannelGroup.ListAll();
            #else //MP11BETA or SVN
                    IList<RadioChannelGroup> allradiogroups = RadioChannelGroup.ListAll();
            #endif

                    foreach (RadioChannelGroup tmpRadioGroup in allradiogroups)
                    {
                        tmpRadioGroup.Delete();
                        radiochannelGroupCount++;
                    }

                    textoutput(radiochannelGroupCount + " radio groups deleted");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_DeleteAllRadioGroups);

                }

                //import servers and cards
                if (server == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_Servers);
                    textoutput("Importing server settings");

                    Server dbserver = null;
                    Card dbserverCard = null;

                    XmlNodeList serverList = doc.SelectNodes("/tvserver/servers/server");
                    serverCount = 0;
                    foreach (XmlNode nodeserver in serverList)
                    {

                        serverCount++;
                        int serverid = Convert.ToInt32(nodeserver.Attributes["IdServer"].Value);
                        try
                        {
                            dbserver = Server.Retrieve(serverid);
                            // check for identical Hostname
                            if (dbserver.HostName != nodeserver.Attributes["HostName"].Value)
                            {
                                textoutput("<RED>Server hostname " + dbserver.HostName + " does not match import data " + nodeserver.Attributes["HostName"].Value);
                                switch (myMessageBox("Do you want to cancel the import? This is recommended! \n\n ", "Server hostname " + dbserver.HostName + " does not match import data " + nodeserver.Attributes["HostName"].Value, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
                                {
                                    case DialogResult.Yes: // Abort
                                        {
                                            textoutput("User is aborting import");
                                            return (false);
                                        }

                                    case DialogResult.No: //  Continue
                                        {
                                            textoutput("User continues import although server name does not match host");
                                            break;
                                        }
                                }
                            }
                            //Server settings are in SetupTV\Sections\Servers.cs : private void buttonMaster_Click
                            dbserver.IsMaster = Convert.ToBoolean(nodeserver.Attributes["IsMaster"].Value);
            #if(MP13)
                            try
                            {
                                dbserver.RtspPort = Convert.ToInt32(nodeserver.Attributes["RtspPort"].Value);
                            }
                            catch //do nothing
                            {
                            }

            #endif
                            dbserver.Persist();

                            // global scanning parameters which are saved as server attributes

                            PostImport(doc, nodeserver, "lnbDefault");
                            PostImport(doc, nodeserver, "LnbLowFrequency");
                            PostImport(doc, nodeserver, "LnbHighFrequency");
                            PostImport(doc, nodeserver, "LnbSwitchFrequency");

                        }
                        catch (Exception exc)
                        {
                            textoutput("<RED>Servers: Failed to add server " + serverid);
                            if (DEBUG == true)
                            {
                                textoutput("<RED>Exception message is " + exc.Message);
                            }
                            return false;
                        }

                    }
                    textoutput(serverCount + " Server settings imported");

                    // Cards
                    textoutput("Importing card settings");

                    //case a: match id and name and devicepath
                    i = 1;
                    foreach (XmlNode nodecard in cardList)
                    {
                        if (i > allTVcards.Count) //stop if there are more xml cards than tv cards, id cannot match anymore
                            break;

                        //int cardid = Convert.ToInt32(nodecard.Attributes["IdCard"].Value);
                        int cardid = i;

                        string name = nodecard.Attributes["Name"].Value;
                        string devicepath = nodecard.Attributes["DevicePath"].Value;

                        if ((cardidpos[i] == TVcards[i].IdCard) && (name == TVcards[i].Name) && (devicepath == TVcards[i].DevicePath) && (TVcardassigned[i] == false) && (xmlcardassigned[i] == false))
                        {
                            if (DEBUG == true)
                                textoutput("Card id " + TVcards[i].IdCard.ToString() + " maped to .xml id " + cardidpos[i].ToString() + " name " + name + " (matched id, name, devicepath)");

                            cardmaptranslator[i] = i;
                            TVcardassigned[i] = true;
                            xmlcardassigned[i] = true;
                        }
                        i++;
                    }

                    //case b: match id and name
                    i = 1;
                    foreach (XmlNode nodecard in cardList)
                    {
                        if (i > allTVcards.Count) //stop if there are more xml cards than tv cards, id cannot match anymore
                            break;

                        //int cardid = Convert.ToInt32(nodecard.Attributes["IdCard"].Value);
                        int cardid = i;

                        string name = nodecard.Attributes["Name"].Value;
                        string devicepath = nodecard.Attributes["DevicePath"].Value;

                        if ((cardidpos[i] == TVcards[i].IdCard) && (name == TVcards[i].Name) && (TVcardassigned[i] == false) && (xmlcardassigned[i] == false))
                        {
                            if (DEBUG == true)
                                textoutput("Card id " + TVcards[i].IdCard.ToString() + " maped to .xml id " + cardidpos[i].ToString() + " name " + name + " (matched id, name)");

                            cardmaptranslator[i] = i;
                            TVcardassigned[i] = true;
                            xmlcardassigned[i] = true;

                        }
                        i++;

                    }
                    //case c: match name and devicepath
                    foreach (XmlNode nodecard in cardList)
                    {

                        int cardid = Convert.ToInt32(nodecard.Attributes["IdCard"].Value);
                        int cardidposition = 0;
                        for (int j = 1; j <= xmlcardnumbers; j++)
                        {
                            if (cardid == cardidpos[j])
                            {
                                cardidposition = j;
                                break;
                            }
                        }
                        if (cardidposition == 0)
                        {
                            textoutput("<RED>Card ID position for card number " + cardid.ToString() + "could not be identified - aborting import");
                            return false;
                        }

                        string name = nodecard.Attributes["Name"].Value;
                        string devicepath = nodecard.Attributes["DevicePath"].Value;
                        for (i = 1; i <= allTVcards.Count; i++)
                        {
                            if ((name == TVcards[i].Name) && (devicepath == TVcards[i].DevicePath) && (TVcardassigned[i] == false) && (xmlcardassigned[cardidposition] == false))
                            {
                                if (DEBUG == true)
                                    textoutput("Card id " + TVcards[i].IdCard.ToString() + " maped to .xml id " + cardid.ToString() + " name " + name + " \n(matched name, devicepath)");

                                cardmaptranslator[cardidposition] = i;
                                TVcardassigned[i] = true;
                                xmlcardassigned[cardidposition] = true;
                            }
                        }

                    }
                    //case d: match name
                    foreach (XmlNode nodecard in cardList)
                    {

                        int cardid = Convert.ToInt32(nodecard.Attributes["IdCard"].Value);
                        int cardidposition = 0;
                        for (int j = 1; j <= xmlcardnumbers; j++)
                        {
                            if (cardid == cardidpos[j])
                            {
                                cardidposition = j;
                                break;
                            }
                        }
                        if (cardidposition == 0)
                        {
                            textoutput("<RED>Card ID position for card number " + cardid.ToString() + "could not be identified - aborting import");
                            return false;
                        }

                        string name = nodecard.Attributes["Name"].Value;
                        string devicepath = nodecard.Attributes["DevicePath"].Value;
                        for (i = 1; i <= allTVcards.Count; i++)
                        {
                            if ((name == TVcards[i].Name) && (TVcardassigned[i] == false) && (xmlcardassigned[cardidposition] == false))
                            {
                                if (DEBUG == true)
                                    textoutput("Card id " + TVcards[i].IdCard.ToString() + " maped to .xml id " + cardid.ToString() + " name " + name + " \n(matched name)");

                                cardmaptranslator[cardidposition] = i;
                                TVcardassigned[i] = true;
                                xmlcardassigned[cardidposition] = true;
                            }
                        }

                    }
                    for (i = 1; i <= allTVcards.Count; i++)
                    {
                        if (TVcardassigned[i] == false)
                        {
                            textoutput("<YELLOW>TV card ID " + TVcards[i].IdCard.ToString() + " with name " + TVcards[i].Name + " has not been assigned to a card from the backup data - no channel will be assigned to this card");
                        }
                    }
                    for (i = 1; i <= allXMLcards; i++)
                    {
                        if (xmlcardassigned[i] == false)
                        {
                            textoutput("<YELLOW>TV card ID " + cardidpos[i].ToString() + " from backup data could not assigned to a TV server card - card data will be skipped");

                        }
                    }

                    // now import card attributes
                    //cardList = doc.SelectNodes("/tvserver/servers/server/cards/card");
                    cardCount = 0;
                    foreach (XmlNode nodecard in cardList)
                    {

                        int cardid = Convert.ToInt32(nodecard.Attributes["IdCard"].Value);
                        int cardidposition = 0;
                        for (int j = 1; j <= xmlcardnumbers; j++)
                        {
                            if (cardid == cardidpos[j])
                            {
                                cardidposition = j;
                                break;
                            }
                        }
                        if (cardidposition == 0)
                        {
                            textoutput("<RED>Card ID position for card number " + cardid.ToString() + "could not be identified - aborting import");
                            return false;
                        }

                        if (xmlcardassigned[cardidposition] == true) //cardmapping does exist
                        {
                            try
                            {
                                dbserverCard = TVcards[cardmaptranslator[cardidposition]];
                                cardCount++;

                                // check for identical card names
                                if (dbserverCard.Name != nodecard.Attributes["Name"].Value)
                                {
                                    textoutput("<RED>Card name of cardid " + cardid + " does not match import data - aborting import");
                                    return false;
                                }
                                dbserverCard.RecordingFolder = nodecard.Attributes["RecordingFolder"].Value;
                                checkfilepath(dbserverCard.RecordingFolder, "recording folder card " + cardidposition.ToString());
                                dbserverCard.TimeShiftFolder = nodecard.Attributes["TimeShiftFolder"].Value;
                                checkfilepath(dbserverCard.TimeShiftFolder, "time shift folder card " + cardidposition.ToString());
                                // check for directory existence and write access

                                dbserverCard.RecordingFormat = Convert.ToInt32(nodecard.Attributes["RecordingFormat"].Value);
                                dbserverCard.Enabled = Convert.ToBoolean(nodecard.Attributes["Enabled"].Value);
                                dbserverCard.GrabEPG = Convert.ToBoolean(nodecard.Attributes["GrabEPG"].Value);
                                dbserverCard.Priority = Convert.ToInt32(nodecard.Attributes["Priority"].Value);

            #if(MP100)
                                //do nothing
            #elif(MP101)
                                //do nothing
            #else //MP11BETA or SVN
                                try
                                {
                                    dbserverCard.CAM = Convert.ToBoolean(nodecard.Attributes["CAM"].Value);
                                    dbserverCard.PreloadCard = Convert.ToBoolean(nodecard.Attributes["PreloadCard"].Value);
                                    dbserverCard.netProvider = Convert.ToInt32(nodecard.Attributes["netProvider"].Value); //bugfix: added 15.08.2010
                                }
                                catch
                                {
                                    //do nothing
                                }
            #endif

            #if(MP13)
                                try
                                {
                                    dbserverCard.CAM = Convert.ToBoolean(nodecard.Attributes["StopGraph"].Value);
                                }
                                catch //do nothing
                                {
                                }

            #endif

                                dbserverCard.CamType = Convert.ToInt32(nodecard.Attributes["CamType"].Value);
                                dbserverCard.DecryptLimit = Convert.ToInt32(nodecard.Attributes["DecryptLimit"].Value);

                                dbserverCard.Persist();

                                //Import card settings for scanning
                                //NOTFOUND values are filtered out during Tvserverimport
                                //Analog
                                PostImport(doc, nodecard, "analog" + dbserverCard.IdCard.ToString() + "Country", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "analog" + dbserverCard.IdCard.ToString() + "Source", "BACKUPSETTINGS_NOTFOUND");
                                //ATSC
                                PostImport(doc, nodecard, "atsc" + dbserverCard.IdCard.ToString() + "supportsqam", "BACKUPSETTINGS_NOTFOUND");
                                //DVBC
                                PostImport(doc, nodecard, "dvbc" + dbserverCard.IdCard.ToString() + "Country", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbc" + dbserverCard.IdCard.ToString() + "creategroups", "BACKUPSETTINGS_NOTFOUND");
                                //DVBS
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "SatteliteContext1", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "SatteliteContext2", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "SatteliteContext3", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "SatteliteContext4", "BACKUPSETTINGS_NOTFOUND");

                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "DisEqc1", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "DisEqc2", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "DisEqc3", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "DisEqc4", "BACKUPSETTINGS_NOTFOUND");

                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "band1", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "band2", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "band3", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "band4", "BACKUPSETTINGS_NOTFOUND");

                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "LNB1", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "LNB2", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "LNB3", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "LNB4", "BACKUPSETTINGS_NOTFOUND");

                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "creategroups", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "creategroupssat", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "createsignalgroup", "BACKUPSETTINGS_NOTFOUND");

                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "enabledvbs2", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "limitsEnabled", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "motorEnabled", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "motorStepSize", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbs" + dbserverCard.IdCard.ToString() + "selectedMotorSat", "BACKUPSETTINGS_NOTFOUND");
                                //DVBT
                                PostImport(doc, nodecard, "dvbt" + dbserverCard.IdCard.ToString() + "Country", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbt" + dbserverCard.IdCard.ToString() + "creategroups", "BACKUPSETTINGS_NOTFOUND");
                                //DVBIP
                                PostImport(doc, nodecard, "dvbip" + dbserverCard.IdCard.ToString() + "Service", "BACKUPSETTINGS_NOTFOUND");
                                PostImport(doc, nodecard, "dvbip" + dbserverCard.IdCard.ToString() + "creategroups", "BACKUPSETTINGS_NOTFOUND");

                            }
                            catch (Exception exc)
                            {
                                textoutput("<RED>Cards: Failed to add card attributes for card ID " + cardid);
                                if (DEBUG == true)
                                {
                                    textoutput("<RED>Exception message is " + exc.Message);
                                }
                                return false;
                            }
                        }

                    }
                    textoutput(cardCount + " Card settings imported");
                    identicalCards = true; // card and server names do match import file

                    //Import DiSEqC motor settings
                    textoutput("Importing DiSEqC motor settings");
                    motorCount = 0;
                    XmlNodeList motorList = doc.SelectNodes("/tvserver/DiSEqCmotors/motor");
                    foreach (XmlNode nodemotor in motorList)
                    {
                        if ((CompareVersions(ActualTvServerVersion, "1.0.3.0") == (int)COMPAREVERSION.NEWER) && (CompareVersions(BackupTvServerVersion, "1.0.3.0") == (int)COMPAREVERSION.OLDER))
                        {
                            myMessageBox("Satellite file names have been changed in your actual version\nDisEqc settings will not get imported", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                            textoutput("<RED>Satellite file names have been changed in your actual version\nDisEqc settings will not get imported");
                            break;
                        }
                        else if ((CompareVersions(BackupTvServerVersion, "1.0.3.0") == (int)COMPAREVERSION.NEWER) && (CompareVersions(ActualTvServerVersion, "1.0.3.0") == (int)COMPAREVERSION.OLDER))
                        {
                            myMessageBox("Satellite file names have been changed in your actual version\nDisEqc settings will not get imported", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                            textoutput("<RED>Satellite file names have been changed in your actual version\nDisEqc settings will not get imported");
                            break;
                        }
                        else // DisEqc settingsb will get imported
                        {
                            try
                            {
                                motorCount++;

                                int cardidmotor = Convert.ToInt32(nodemotor.Attributes["IdCard"].Value);
                                int cardidposition = 0;
                                for (int j = 1; j <= xmlcardnumbers; j++)
                                {
                                    if (cardidmotor == cardidpos[j])
                                    {
                                        cardidposition = j;
                                        break;
                                    }
                                }
                                if (cardidposition == 0)
                                {
                                    textoutput("<RED>Card ID position for card number " + cardidmotor.ToString() + "could not be identified - aborting import");
                                    return false;
                                }
                                int idcardunmapped = cardidposition;

                                if (xmlcardassigned[idcardunmapped] == true)
                                {

                                    //check if satellite does exist
                                    string satelliteName = nodemotor.Attributes["SatelliteName"].Value;
                                    string transponderFileName = nodemotor.Attributes["TransponderFileName"].Value;

                                    Satellite satellite = null;
            #if(MP100)
                                IList allsatellites = Satellite.ListAll();
            #elif(MP101)
                                IList<Satellite> allsatellites = Satellite.ListAll();
            #else //MP11BETA or SVN
                                    IList<Satellite> allsatellites = Satellite.ListAll();
            #endif

                                    foreach (Satellite sat in allsatellites)
                                    {
                                        if ((sat.SatelliteName == satelliteName) && (sat.TransponderFileName == transponderFileName))
                                        {
                                            satellite = sat;
                                            if (DEBUG == true)
                                                textoutput("Existing satellite id " + satellite.IdSatellite + " found for name " + satellite.SatelliteName);

                                            break;
                                        }
                                    }

                                    if (satellite == null)
                                    {
                                        //create new satellite
                                        satellite = new Satellite(satelliteName, transponderFileName);

                                        if (satellite == null)
                                        {
                                            textoutput("<RED>Could not create new satellite for " + satelliteName + " with transponder filename \n" + transponderFileName);
                                            return false;
                                        }
                                        satellite.Persist();
                                        if (DEBUG == true)
                                            textoutput("New satellite id " + satellite.IdSatellite + " created for name " + satellite.SatelliteName);

                                    }

                                    if (File.Exists(transponderFileName) == false)
                                    {

                                        //try to translate path
                                        if (transponderFileName.Contains("Tuningparameters") == true)
                                        {
                                            int pos = transponderFileName.IndexOf("Tuningparameters");
                                            string partialfilename = transponderFileName.Substring(pos, transponderFileName.Length - pos);
            #if(MP100)
                                        string newtransponderFileName = TV_PROGRAM_FOLDER + @"\" + partialfilename;
            #elif(MP101)
                                        string newtransponderFileName = TV_PROGRAM_FOLDER + @"\" + partialfilename;
            #else //MP11BETA or SVN
                                            string newtransponderFileName = TV_USER_FOLDER + @"\" + partialfilename;
            #endif

                                            if (File.Exists(newtransponderFileName) == true)
                                            {
                                                if (DEBUG == true)
                                                    textoutput("Renaming transponder filename \n" + transponderFileName + "\nto " + newtransponderFileName);

                                                satellite.TransponderFileName = newtransponderFileName;
                                                satellite.Persist();
                                            }
                                            else
                                            {
                                                textoutput("<RED>Renamed transponder filename " + newtransponderFileName + " does not exist for satellite" + satelliteName);
                                                return false;
                                            }
                                        }
                                        else
                                        {
                                            textoutput("<RED>Transponder filename " + transponderFileName + " does not exist for satellite" + satelliteName);
                                            return false;
                                        }
                                    }
                                    //check if motorsetting does exist

                                    int cardid = TVcards[cardmaptranslator[idcardunmapped]].IdCard;
                                    int position = Convert.ToInt32(nodemotor.Attributes["Position"].Value);

                                    DiSEqCMotor motor = null;
            #if(MP100)
                                IList allmotors = DiSEqCMotor.ListAll();
            #elif(MP101)
                                IList<DiSEqCMotor> allmotors = DiSEqCMotor.ListAll();
            #else //MP11BETA or SVN
                                    IList<DiSEqCMotor> allmotors = DiSEqCMotor.ListAll();
            #endif

                                    foreach (DiSEqCMotor mot in allmotors)
                                    {
                                        if ((mot.IdCard == cardid) && (mot.IdSatellite == satellite.IdSatellite))
                                        {
                                            motor = mot;
                                            if (DEBUG == true)
                                                textoutput("Existing motor id " + motor.IdDiSEqCMotor + " found for satellite " + satellite.SatelliteName + " and card id " + cardid);

                                            break;
                                        }
                                    }

                                    if (motor == null)
                                    {
                                        //create new motor
                                        motor = new DiSEqCMotor(cardid, satellite.IdSatellite, position);
                                        if (DEBUG == true)
                                            textoutput("New DiSEqC motor created for satellite " + satellite.SatelliteName + " and card id " + cardid);

                                    }

                                    //update values
                                    motor.IdCard = cardid;
                                    motor.IdSatellite = satellite.IdSatellite;
                                    motor.Position = position;
                                    motor.Persist();
                                    if (DEBUG == true)
                                        textoutput("DiSEqC motor id " + motor.IdDiSEqCMotor + " wirth cardid " + motor.IdCard + " and position " + motor.Position + " has been processed successfully");
                                }
                            }
                            catch (Exception exc)
                            {
                                motorCount--;
                                textoutput("<RED>Failed to add/update DiSEqC Motor ");
                                if (DEBUG == true)
                                {
                                    textoutput("<RED>Exception message is " + exc.Message);
                                }
                                return false;
                            }

                        }
                    }
                    textoutput(motorCount + " DiSEqC motor settings imported");

                    // Hybrid Settings
                    textoutput("Importing hybrid card settings");

                    // Delete old groups
            #if(MP100)
                    IList hybridcardgroups = CardGroup.ListAll();
            #elif(MP101)
                    IList<CardGroup> hybridcardgroups = CardGroup.ListAll();
            #else //MP11BETA or SVN
                    IList<CardGroup> hybridcardgroups = CardGroup.ListAll();
            #endif

                    int cardgroupCount = 0;
                    foreach (CardGroup hybridcardgroup in hybridcardgroups)
                    {
                        cardgroupCount++;
                        try
                        {
                            hybridcardgroup.Delete();
                        }
                        catch (Exception exc)
                        {
                            textoutput("<RED>Failed to delete hybrid card group " + hybridcardgroup.IdCardGroup + " named " + hybridcardgroup.Name);
                            if (DEBUG == true)
                            {
                                textoutput("<RED>Exception message is " + exc.Message);
                            }
                            return false;
                        }
                    }
                    textoutput(cardgroupCount + " Old hybrid groups deleted");

                    XmlNodeList cardgroupList = doc.SelectNodes("/tvserver/HybridCardGroups/HybridCardGroup");
                    cardgroupCount = 0;
                    foreach (XmlNode nodecardgroup in cardgroupList)
                    {
                        cardgroupCount++;
                        int newIdCardGroup = Convert.ToInt32(nodecardgroup.Attributes["IdCardGroup"].Value);
                        string newname = nodecardgroup.Attributes["CardGroupName"].Value;
                        try
                        {
                            CardGroup newcardgroup = new CardGroup(newIdCardGroup, newname);
                            newcardgroup.Persist();
                        }
                        catch (Exception exc)
                        {
                            textoutput("<RED>CardGroups: Failed to add card group attributes for card group " + newIdCardGroup + " named " + newname);
                            if (DEBUG == true)
                            {
                                textoutput("<RED>Exception message is " + exc.Message);
                            }
                            return false;
                        }
                    }
                    textoutput(cardgroupCount + " hybrid groups imported");

                    XmlNodeList cardgroupmapList = doc.SelectNodes("/tvserver/HybridCardGroupMaps/HybridCardGroupMap");
                    int cardgroupmapCount = 0;

                    foreach (XmlNode nodecardgroupmap in cardgroupmapList)
                    {
                        cardgroupmapCount++;
                        int newIdCardGroupMap = Convert.ToInt32(nodecardgroupmap.Attributes["IdMapping"].Value);
                        int newIdCardGroup = Convert.ToInt32(nodecardgroupmap.Attributes["IdCardGroup"].Value);

                        //int newIdCardunmapped = Convert.ToInt32(nodecardgroupmap.Attributes["IdCard"].Value);

                        int cardid = Convert.ToInt32(nodecardgroupmap.Attributes["IdCard"].Value);
                        int cardidposition = 0;
                        for (int j = 1; j <= xmlcardnumbers; j++)
                        {
                            if (cardid == cardidpos[j])
                            {
                                cardidposition = j;
                                break;
                            }
                        }
                        if (cardidposition == 0)
                        {
                            textoutput("<RED>Card ID position for card number " + cardid.ToString() + "could not be identified - aborting import");
                            return false;
                        }
                        int newIdCardunmapped = cardidposition;

                        string HybridGroupName = nodecardgroupmap.Attributes["HybridGroupName"].Value;
                        if (xmlcardassigned[newIdCardunmapped] == true) //cardmapping does exist
                        {
                            int newIdCard = TVcards[cardmaptranslator[newIdCardunmapped]].IdCard;

                            try
                            {

                                POSTIMPORT += "CARDGROUPMAP\t" + newIdCard + "\t" + newIdCardGroup + "\t" + HybridGroupName + "\n";

                                if (DEBUG == true)
                                {
                                    textoutput("newIdCard =" + newIdCard + " newIdCardGroup=" + newIdCardGroup);
                                }
                            }
                            catch (Exception exc)
                            {
                                textoutput("<RED>CardGroupMappings: Failed to add card group mapping " + newIdCardGroupMap + "Error: " + exc.Message);

                            }
                        }
                    }

                    textoutput(cardgroupCount + " Hybrid Groups with " + cardgroupmapCount + " Card Mappings imported");

                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_Servers);
                }

                if (identicalCards == false) // do not import channelmappings if cards and servers are not identical from importfile
                {
                    channelcardmappings = false;
                    textoutput("<YELLOW>Servers and cards box unchecked - will not import channel mappings");
                }

                // Import Channels
                if (channels == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_Channels);
                    textoutput("Importing channel settings - Please be patient");
                    XmlNodeList channelList = doc.SelectNodes("/tvserver/channels/channel");
                    channelCount = 0;

                    foreach (XmlNode nodeChannel in channelList)
                    {

                        string name = nodeChannel.Attributes["DisplayName"].Value;  //use only displayname
                        int IdChannel = Int32.Parse(GetNodeAttribute(nodeChannel, "IdChannel", "0"));
                        try
                        {
                            channelCount++;
                            Channel dbChannel = null;

                            XmlNodeList tuningList = nodeChannel.SelectNodes("TuningDetails/tune");
                            XmlNodeList mappingList = nodeChannel.SelectNodes("mappings/map");

                            bool grabEpg = (GetNodeAttribute(nodeChannel, "GrabEpg", "True") == "True");
                            bool isRadio = (GetNodeAttribute(nodeChannel, "IsRadio", "False") == "True");
                            bool isTv = (GetNodeAttribute(nodeChannel, "IsTv", "True") == "True");
                            DateTime lastGrabTime = DateTime.ParseExact("2000-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                            DateTime totalTimeWatched = DateTime.ParseExact("2000-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

                            try
                            {
                                lastGrabTime = DateTime.ParseExact(GetNodeAttribute(nodeChannel, "LastGrabTime", "1900-01-01 00:00:00"), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                                totalTimeWatched = DateTime.ParseExact(GetNodeAttribute(nodeChannel, "TotalTimeWatched", "1900-01-01 00:00:00"), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                            }
                            catch
                            {
                                textoutput("<RED>Date and time could not be parsed for LastGrabTime and TotalTimeWatched - skipping values");
                            }
                            int sortOrder = Int32.Parse(GetNodeAttribute(nodeChannel, "SortOrder", "0"));
                            int timesWatched = Int32.Parse(GetNodeAttribute(nodeChannel, "TimesWatched", "0"));

                            bool visibileInGuide = (GetNodeAttribute(nodeChannel, "VisibleInGuide", "True") == "True");
                            bool FreeToAir = (GetNodeAttribute(nodeChannel, "FreeToAir", "True") == "True");
                            string displayName = GetNodeAttribute(nodeChannel, "DisplayName", name);
                            bool epgHasGaps = (GetNodeAttribute(nodeChannel, "EpgHasGaps", "False") == "True");
                            string externalId = GetNodeAttribute(nodeChannel, "ExternalId", "0");

                            // rtv: since analog allows NOT to merge channels we need to take care of this. US users e.g. have multiple stations named "Sport" with different tuningdetails.
                            // using AddChannel would incorrectly "merge" these totally different channels.
                            // see this: http://forum.team-mediaportal.com/1-0-rc1-svn-builds-271/importing-exported-channel-list-groups-channels-39368/

                            /*
                            if (DEBUG == true)
                            {
                                Log.Info("TvChannels: Adding {0}. channel: {1} ({2})", channelCount, name, displayName);
                            }*/
                            dbChannel = layer.AddNewChannel(name);
                            if (dbChannel == null)
                            {
                                textoutput("<RED>Failed to add channel " + name + " - aborting import");
                                return false;
                            }
                            dbChannel.GrabEpg = grabEpg;
                            dbChannel.IsRadio = isRadio;
                            dbChannel.IsTv = isTv;
                            dbChannel.LastGrabTime = lastGrabTime;
                            dbChannel.SortOrder = sortOrder;
                            dbChannel.TimesWatched = timesWatched;
                            dbChannel.TotalTimeWatched = totalTimeWatched;
                            dbChannel.VisibleInGuide = visibileInGuide;

            #if (MP12)
            #else
                            try
                            {
                                dbChannel.FreeToAir = FreeToAir;
                            }
                            catch //do nothing
                            {

                            }
            #endif
                            dbChannel.DisplayName = displayName;  //possible bug
                            dbChannel.EpgHasGaps = epgHasGaps;
                            dbChannel.ExternalId = externalId;

            #if(MP13)
                                        try
                                        {
                                            dbChannel.ChannelNumber = Int32.Parse(GetNodeAttribute(nodeChannel, "ChannelNumber", "10000"));

                                            //Ilist string Groupnames
                                            //Group CurrentGroup
                                            //program CurrentProgram
                                            //program NextProgram
                                        }
                                        catch //do nothing
                                        {
                                        }
            #endif

                            dbChannel.Persist();
                            if (channelcardmappings == true)
                            {
                                foreach (XmlNode nodeMap in mappingList)
                                {
                                    int idCard = Int32.Parse(nodeMap.Attributes["IdCard"].Value);

                                    //get xml position
                                    bool mapflag = false;
                                    for (int j = 1; j <= allXMLcards; j++)
                                    {
                                        if (idCard == cardidpos[j])  //position of card can be different to id
                                        {
                                            if (xmlcardassigned[cardmaptranslator[j]] == true)
                                            {
                                                try
                                                {
                                                    layer.MapChannelToCard(TVcards[cardmaptranslator[j]], dbChannel, false);
                                                    mapflag = true;
                                                }
                                                catch (Exception exe)
                                                {
                                                    textoutput("<RED>Failed to map channel " + dbChannel.DisplayName + " to card id " + cardmaptranslator[j].ToString());
                                                    textoutput("<RED>Exception message is " + exe.Message);
                                                }
                                            }

                                        }
                                    }
                                    if (mapflag == false)
                                    {
                                        textoutput("<RED>Failed to map channel " + dbChannel.DisplayName + " to any card");
                                    }

                                }
                            }

                            foreach (XmlNode nodeTune in tuningList)
                            {

            #if (MP12)
            #else
                                int pcrPid = -1;
                                int audioPid = -1;
                                int videoPid = -1;

                                try
                                {
                                    pcrPid = Int32.Parse(nodeTune.Attributes["PcrPid"].Value);
                                }
                                catch { }

                                try
                                {
                                    audioPid = Int32.Parse(nodeTune.Attributes["AudioPid"].Value);
                                }
                                catch { }

                                try
                                {
                                    videoPid = Int32.Parse(GetNodeAttribute(nodeTune, "VideoPid", "-1"));
                                }
                                catch { }

            #endif
                                int bandwidth = Int32.Parse(nodeTune.Attributes["Bandwidth"].Value);
                                int channelNumber = Int32.Parse(nodeTune.Attributes["ChannelNumber"].Value);
                                int channelType = Int32.Parse(nodeTune.Attributes["ChannelType"].Value);
                                int countryId = Int32.Parse(nodeTune.Attributes["CountryId"].Value);
                                int diseqc = Int32.Parse(nodeTune.Attributes["Diseqc"].Value);
                                bool fta = (nodeTune.Attributes["FreeToAir"].Value == "True");
                                int frequency = Int32.Parse(nodeTune.Attributes["Frequency"].Value);
                                int majorChannel = Int32.Parse(nodeTune.Attributes["MajorChannel"].Value);
                                int minorChannel = Int32.Parse(nodeTune.Attributes["MinorChannel"].Value);
                                int modulation = Int32.Parse(nodeTune.Attributes["Modulation"].Value);
                                name = nodeTune.Attributes["Name"].Value;
                                int networkId = Int32.Parse(nodeTune.Attributes["NetworkId"].Value);
                                int pmtPid = Int32.Parse(nodeTune.Attributes["PmtPid"].Value);
                                int polarisation = Int32.Parse(nodeTune.Attributes["Polarisation"].Value);
                                string provider = GetNodeAttribute(nodeTune, "Provider", "");
                                int serviceId = Int32.Parse(nodeTune.Attributes["ServiceId"].Value);
                                int switchingFrequency = Int32.Parse(nodeTune.Attributes["SwitchingFrequency"].Value);
                                int symbolrate = Int32.Parse(nodeTune.Attributes["Symbolrate"].Value);
                                int transportId = Int32.Parse(nodeTune.Attributes["TransportId"].Value);
                                int tuningSource = Int32.Parse(GetNodeAttribute(nodeTune, "TuningSource", "0"));
                                int videoSource = Int32.Parse(GetNodeAttribute(nodeTune, "VideoSource", "0"));
                                int audioSource = Int32.Parse(GetNodeAttribute(nodeTune, "AudioSource", "0"));
                                int SatIndex = Int32.Parse(GetNodeAttribute(nodeTune, "SatIndex", "-1"));
                                int InnerFecRate = Int32.Parse(GetNodeAttribute(nodeTune, "InnerFecRate", "-1"));
                                int band = Int32.Parse(GetNodeAttribute(nodeTune, "Band", "0"));
                                int pilot = Int32.Parse(GetNodeAttribute(nodeTune, "Pilot", "-1"));
                                int rollOff = Int32.Parse(GetNodeAttribute(nodeTune, "RollOff", "-1"));
                                string url = GetNodeAttribute(nodeTune, "Url", "");
                                int bitrate = Int32.Parse(GetNodeAttribute(nodeTune, "Bitrate", "0"));
                                bool isVCRSignal = (GetNodeAttribute(nodeChannel, "IsVCRSignal", "False") == "True");

                                switch (channelType)
                                {
                                    case 0: //AnalogChannel
                                        AnalogChannel analogChannel = new AnalogChannel();
                                        if (analogChannel == null)
                                        {
                                            textoutput("<RED>Could not create analog channel for " + name);
                                            return false;
                                        }
                                        analogChannel.ChannelNumber = channelNumber;
                                        analogChannel.Country = collection.Countries[countryId];
                                        analogChannel.Frequency = frequency;
                                        analogChannel.IsRadio = isRadio;
                                        analogChannel.IsTv = isTv;
                                        analogChannel.Name = name;
                                        analogChannel.TunerSource = (TunerInputType)tuningSource;
                                        analogChannel.VideoSource = (AnalogChannel.VideoInputType)videoSource;
            #if(MP100)
                                        //do nothing
            #elif(MP101)
                                        //do nothing
            #else //MP11BETA or SVN
                                        analogChannel.AudioSource = (AnalogChannel.AudioInputType)audioSource;
                                        analogChannel.IsVCRSignal = isVCRSignal;
            #endif

                                        layer.AddTuningDetails(dbChannel, analogChannel);
                                        if (DEBUG)
                                            Log.Info("TvChannels: Added tuning details for analog channel: {0} number: {1}", name, channelNumber);

                                        break;
                                    case 1: //ATSCChannel
                                        ATSCChannel atscChannel = new ATSCChannel();
                                        if (atscChannel == null)
                                        {
                                            textoutput("<RED>Could not create ATSC channel for " + name);
                                            return false;
                                        }
                                        atscChannel.MajorChannel = majorChannel;
                                        atscChannel.MinorChannel = minorChannel;
                                        atscChannel.PhysicalChannel = channelNumber;
                                        atscChannel.LogicalChannelNumber = channelNumber;
                                        atscChannel.FreeToAir = fta;
                                        atscChannel.Frequency = frequency;
                                        atscChannel.IsRadio = isRadio;
                                        atscChannel.IsTv = isTv;
                                        atscChannel.Name = name;
                                        atscChannel.NetworkId = networkId;
            #if (MP12)
            #else
                                        if (pcrPid > -1)
                                            atscChannel.PcrPid = pcrPid;

                                        if (audioPid > -1)
                                            atscChannel.AudioPid = audioPid;

                                        if (videoPid > -1)
                                            atscChannel.VideoPid = videoPid;
            #endif
                                        atscChannel.PmtPid = pmtPid;
                                        atscChannel.Provider = provider;
                                        atscChannel.ServiceId = serviceId;
                                        //atscChannel.SymbolRate = symbolrate;
                                        atscChannel.TransportId = transportId;
                                        atscChannel.ModulationType = (ModulationType)modulation;
                                        layer.AddTuningDetails(dbChannel, atscChannel);

                                        if (DEBUG)
                                            Log.Info("TvChannels: Added tuning details for ATSC channel: {0} number: {1} provider: {2}", name, channelNumber, provider);

                                        break;
                                    case 2: //DVBCChannel
                                        DVBCChannel dvbcChannel = new DVBCChannel();
                                        if (dvbcChannel == null)
                                        {
                                            textoutput("<RED>Could not create DVB channel for " + name);
                                            return false;
                                        }
                                        dvbcChannel.ModulationType = (ModulationType)modulation;
                                        dvbcChannel.FreeToAir = fta;
                                        dvbcChannel.Frequency = frequency;
                                        dvbcChannel.IsRadio = isRadio;
                                        dvbcChannel.IsTv = isTv;
                                        dvbcChannel.Name = name;
                                        dvbcChannel.NetworkId = networkId;
            #if (MP12)
            #else
                                        if (pcrPid > -1)
                                            dvbcChannel.PcrPid = pcrPid;

                                        if (audioPid > -1)
                                            dvbcChannel.AudioPid = audioPid;

                                        if (videoPid > -1)
                                            dvbcChannel.VideoPid = videoPid;

            #endif
                                        dvbcChannel.PmtPid = pmtPid;
                                        dvbcChannel.Provider = provider;
                                        dvbcChannel.ServiceId = serviceId;
                                        dvbcChannel.SymbolRate = symbolrate;
                                        dvbcChannel.TransportId = transportId;
                                        dvbcChannel.LogicalChannelNumber = channelNumber;
                                        layer.AddTuningDetails(dbChannel, dvbcChannel);
                                        if (DEBUG)
                                            Log.Info("TvChannels: Added tuning details for DVB-C channel: {0} provider: {1}", name, provider);

                                        break;
                                    case 3: //DVBSChannel
                                        DVBSChannel dvbsChannel = new DVBSChannel();
                                        if (dvbsChannel == null)
                                        {
                                            textoutput("<RED>Could not create DVBS channel for " + name);
                                            return false;
                                        }
                                        dvbsChannel.DisEqc = (DisEqcType)diseqc;
                                        dvbsChannel.Polarisation = (Polarisation)polarisation;
                                        dvbsChannel.SwitchingFrequency = switchingFrequency;
                                        dvbsChannel.FreeToAir = fta;
                                        dvbsChannel.Frequency = frequency;
                                        dvbsChannel.IsRadio = isRadio;
                                        dvbsChannel.IsTv = isTv;
                                        dvbsChannel.Name = name;
                                        dvbsChannel.NetworkId = networkId;
            #if (MP12)
            #else
                                        if (pcrPid > -1)
                                            dvbsChannel.PcrPid = pcrPid;

                                        if (audioPid > -1)
                                            dvbsChannel.AudioPid = audioPid;

                                        if (videoPid > -1)
                                            dvbsChannel.VideoPid = videoPid;
            #endif
                                        dvbsChannel.PmtPid = pmtPid;
                                        dvbsChannel.Provider = provider;
                                        dvbsChannel.ServiceId = serviceId;
                                        dvbsChannel.SymbolRate = symbolrate;
                                        dvbsChannel.TransportId = transportId;
                                        dvbsChannel.SatelliteIndex = SatIndex;
                                        dvbsChannel.ModulationType = (ModulationType)modulation;
                                        dvbsChannel.InnerFecRate = (BinaryConvolutionCodeRate)InnerFecRate;
                                        dvbsChannel.BandType = (BandType)band;
                                        dvbsChannel.Pilot = (Pilot)pilot;
                                        dvbsChannel.Rolloff = (RollOff)rollOff;
                                        dvbsChannel.LogicalChannelNumber = channelNumber;

                                        layer.AddTuningDetails(dbChannel, dvbsChannel);
                                        if (DEBUG)
                                            Log.Info("TvChannels: Added tuning details for DVB-S channel: {0} provider: {1}", name, provider);

                                        break;
                                    case 4: //DVBTChannel
                                        DVBTChannel dvbtChannel = new DVBTChannel();
                                        if (dvbtChannel == null)
                                        {
                                            textoutput("<RED>Could not create DVBT channel for " + name);
                                            return false;
                                        }
                                        dvbtChannel.BandWidth = bandwidth;
                                        dvbtChannel.FreeToAir = fta;
                                        dvbtChannel.Frequency = frequency;
                                        dvbtChannel.IsRadio = isRadio;
                                        dvbtChannel.IsTv = isTv;
                                        dvbtChannel.Name = name;
                                        dvbtChannel.NetworkId = networkId;
            #if (MP12)
            #else
                                        if (pcrPid > -1)
                                            dvbtChannel.PcrPid = pcrPid;

                                        if (audioPid > -1)
                                            dvbtChannel.AudioPid = audioPid;

                                        if (videoPid > -1)
                                            dvbtChannel.VideoPid = videoPid;

            #endif
                                        dvbtChannel.PmtPid = pmtPid;
                                        dvbtChannel.Provider = provider;
                                        dvbtChannel.ServiceId = serviceId;
                                        dvbtChannel.TransportId = transportId;
                                        dvbtChannel.LogicalChannelNumber = channelNumber;

                                        layer.AddTuningDetails(dbChannel, dvbtChannel);
                                        if (DEBUG)
                                            Log.Info("TvChannels: Added tuning details for DVB-T channel: {0} provider: {1}", name, provider);

                                        break;
                                    case 5: //Webstream
                                        layer.AddWebStreamTuningDetails(dbChannel, url, bitrate);
                                        if (DEBUG)
                                            Log.Info("TvChannels: Added wWeb stream: {0} ", url);

                                        break;
                                    //used IP channel from mvedrina patch only for MP1.1 and SVN
            #if(MP100)
                                        //do nothing
            #elif(MP101)
                                        //do nothing
            #else //MP11BETA or SVN

                                    case 7: //DVBIPChannel
                                        DVBIPChannel dvbipChannel = new DVBIPChannel();
            #if (MP12)
            #else
                                        if (pcrPid > -1)
                                            dvbipChannel.PcrPid = pcrPid;

                                        if (audioPid > -1)
                                            dvbipChannel.AudioPid = audioPid;

                                        if (videoPid > -1)
                                            dvbipChannel.VideoPid = videoPid;
            #endif
                                        dvbipChannel.FreeToAir = fta;
                                        dvbipChannel.Frequency = frequency;
                                        dvbipChannel.IsRadio = isRadio;
                                        dvbipChannel.IsTv = isTv;
                                        dvbipChannel.LogicalChannelNumber = channelNumber;
                                        dvbipChannel.Name = name;
                                        dvbipChannel.NetworkId = networkId;
                                        dvbipChannel.PmtPid = pmtPid;
                                        dvbipChannel.Provider = provider;
                                        dvbipChannel.ServiceId = serviceId;
                                        dvbipChannel.TransportId = transportId;
                                        dvbipChannel.Url = url;
                                        layer.AddTuningDetails(dbChannel, dvbipChannel);
                                        if (DEBUG)
                                            Log.Info("TvChannels: Added tuning details for DVB-IP channel: {0} provider: {1}", name, provider);
                                        break;
            #endif
                                }
                            }

                        }
                        catch (Exception exc)
                        {
                            textoutput("<RED>TvChannels: Failed to add channel " + IdChannel + " name " + name);
                            if (DEBUG == true)
                            {
                                textoutput("<RED>Exception message is " + exc.Message);
                            }
                            return false;
                        }

                    }
                    textoutput(channelCount + " channel settings imported");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_Channels);
                }

                if (schedules == true)
                {

                    // begin import schedule settings
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_Schedules);
                    textoutput("Importing schedule settings");

                    XmlNodeList scheduleList = doc.SelectNodes("/tvserver/schedules/schedule");
                    scheduleCount = 0;

                    foreach (XmlNode nodeSchedule in scheduleList)
                    {
                        string programName = nodeSchedule.Attributes["ProgramName"].Value;
                        string displayname = nodeSchedule.Attributes["DisplayName"].Value;
                        int idSchedule = Int32.Parse(nodeSchedule.Attributes["IdSchedule"].Value);
                        try
                        {
                            scheduleCount++;

                            Channel tmpchannel = mygetChannelbyName(displayname);
                            if (tmpchannel == null)
                            {
                                textoutput("<RED>Channel " + displayname + " (Display: " + displayname + ") not found for schedule " + idSchedule);
                            }

                            int idChannel = tmpchannel.IdChannel;
                            DateTime startTime = DateTime.ParseExact(nodeSchedule.Attributes["StartTime"].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

                            DateTime endTime = DateTime.ParseExact(nodeSchedule.Attributes["EndTime"].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                            int scheduletype = Int32.Parse(nodeSchedule.Attributes["ScheduleType"].Value);
                            Schedule schedule = layer.AddSchedule(idChannel, programName, startTime, endTime, scheduletype);
                            schedule.ScheduleType = scheduletype;  //do not remove! AddSchedule(idChannel, programName, startTime,endTime,scheduletype); does not work!
                            schedule.KeepDate = DateTime.ParseExact(nodeSchedule.Attributes["KeepDate"].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                            schedule.PreRecordInterval = Int32.Parse(nodeSchedule.Attributes["PreRecordInterval"].Value);
                            schedule.PostRecordInterval = Int32.Parse(nodeSchedule.Attributes["PostRecordInterval"].Value);
                            schedule.Priority = Int32.Parse(nodeSchedule.Attributes["Priority"].Value);
                            schedule.Quality = Int32.Parse(nodeSchedule.Attributes["Quality"].Value);
                            schedule.Directory = nodeSchedule.Attributes["Directory"].Value;
                            schedule.KeepMethod = Int32.Parse(nodeSchedule.Attributes["KeepMethod"].Value);
                            schedule.MaxAirings = Int32.Parse(nodeSchedule.Attributes["MaxAirings"].Value);
                            schedule.RecommendedCard = 0;
                            try
                            {
                                int unmappedcard = Int32.Parse(nodeSchedule.Attributes["RecommendedCard"].Value);
                                if (xmlcardassigned[unmappedcard] == true) //cardmapping does exist
                                {
                                    schedule.RecommendedCard = cardmaptranslator[unmappedcard];
                                }
                            }
                            catch// do nothing in case of error: recommended card = 0
                            {

                            }
                            schedule.Series = (GetNodeAttribute(nodeSchedule, "Series", "False") == "True");
                            schedule.BitRateMode = (VIDEOENCODER_BITRATE_MODE)Int32.Parse(GetNodeAttribute(nodeSchedule, "BitRateMode", "-1"));
                            schedule.QualityType = (QualityType)Int32.Parse(GetNodeAttribute(nodeSchedule, "QualityType", "1"));

                            try
                            {
                                schedule.Canceled = DateTime.ParseExact(nodeSchedule.Attributes["Canceled"].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                            }
                            catch
                            {
                            }
                            schedule.Persist();

                        }
                        catch (Exception ex)
                        {
                            scheduleCount--;
                            textoutput("<RED>Could not create schedule " + idSchedule + " for " + displayname + " (Display: " + displayname + ") with program " + programName);
                            if (DEBUG)
                            {
                                textoutput("<RED>Exception message is " + ex.Message);
                            }
                            //return false;
                        }

                    }
                    textoutput(scheduleCount + " schedule settings imported");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_Schedules);
                }

                // Import programs
                if (epg == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_EPG);
                    textoutput("Importing program settings - please be patient");

                    XmlNodeList programList = doc.SelectNodes("/tvserver/programs/program");
                    programCount = 0;
                    foreach (XmlNode nodeProgram in programList)
                    {

                        int idProgram = Int32.Parse(nodeProgram.Attributes["IdProgram"].Value);
                        //string channelname = nodeProgram.Attributes["ChannelName"].Value;
                        string displayname = nodeProgram.Attributes["DisplayName"].Value;
                        string title = nodeProgram.Attributes["Title"].Value;
                        try
                        {
                            programCount++;
                            string description = nodeProgram.Attributes["Description"].Value;
                            string classification = nodeProgram.Attributes["Classification"].Value;
                            string episodeNum = nodeProgram.Attributes["EpisodeNum"].Value;
            #if(MP100)
                            //do nothing
            #elif(MP101)
                            //do nothing

            #else //MP11BETA or SVN
                            string episodeName = "";
                            string episodePart = "";
                            try
                            {
                                episodeName = nodeProgram.Attributes["EpisodeName"].Value;
                                episodePart = nodeProgram.Attributes["EpisodePart"].Value;

                            }
                            catch
                            {
                                textoutput("<YELLOW>Warning: Episode name or part not found - will set to \"notavailable\" ");
                                episodeName = "not available";
                                episodePart = "not available";
                            }
            #endif

                            string genre = nodeProgram.Attributes["Genre"].Value;
                            string seriesNum = nodeProgram.Attributes["SeriesNum"].Value;
                            DateTime startTime = DateTime.ParseExact(nodeProgram.Attributes["StartTime"].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                            if (startTime.CompareTo(DateTime.Now) > 0)
                            {
                                DateTime endTime = DateTime.ParseExact(nodeProgram.Attributes["EndTime"].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                                DateTime originalAirDate = DateTime.ParseExact(nodeProgram.Attributes["OriginalAirDate"].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

                                bool notify = false;
                                try
                                {
                                    notify = Convert.ToBoolean(nodeProgram.Attributes["Notify"].Value);
                                }
                                catch //do nothing
                                {

                                }

                                int parentalRating = Int32.Parse(nodeProgram.Attributes["ParentalRating"].Value);
                                int starRating = Int32.Parse(nodeProgram.Attributes["StarRating"].Value);

                                Channel tmpchannel = mygetChannelbyName(displayname);
                                if (tmpchannel == null)
                                {
                                    textoutput("<RED>Channel " + displayname + " (Display: " + displayname + ") not found for program " + idProgram);
                                }
                                int idChannel = tmpchannel.IdChannel;

            #if(MP100)
                                Program program = new Program(idChannel, startTime, endTime, title, description, genre, notify, originalAirDate, seriesNum, episodeNum, starRating, classification, parentalRating);

            #elif (MP101)
                                Program program = new Program(idChannel, startTime, endTime, title, description, genre, notify, originalAirDate, seriesNum, episodeNum, starRating, classification, parentalRating);
            #elif (MP11BETA)
                                Program program = new Program(idChannel, startTime, endTime, title, description, genre, notify, originalAirDate, seriesNum, episodeNum, episodeName, episodePart, starRating, classification, parentalRating);

            #else //SVN 1.0.4.24281
                                Program program = new Program(idChannel, startTime, endTime, title, description, genre, Program.ProgramState.None, originalAirDate, seriesNum, episodeNum, episodeName, episodePart, starRating, classification, parentalRating);

            #endif

                                program.Persist();

                                /*
                                if (DEBUG)
                                    Log.Info("Added program title: {0} on channel: {1} display {2}", title, channelname,displayname);
                                */
                            }
                            else
                            {
                                programCount++;
                            }

                        }
                        catch (Exception ex)
                        {
                            programCount--;
                            textoutput("<RED>Could not create program " + idProgram + " for title " + title + " with program " + displayname + " (Display: " + displayname + ")");
                            if (DEBUG)
                            {
                                textoutput("<RED>Exception message is " + ex.Message);
                            }
                            //return false;
                        }

                    }
                    textoutput(programCount + " program settings imported");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_EPG);
                }

                // Import recordings
                if (recordings == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_Recordings);
                    textoutput("Importing recording settings");

                    XmlNodeList recordingList = doc.SelectNodes("/tvserver/recordings/recording");
                    recordingCount = 0;
                    foreach (XmlNode nodeRecording in recordingList)
                    {
                        string fileName = nodeRecording.Attributes["FileName"].Value;
                        string title = nodeRecording.Attributes["Title"].Value;
                        int idRecording = Int32.Parse(nodeRecording.Attributes["IdRecording"].Value);
                        try
                        {
                            recordingCount++;

                            string description = nodeRecording.Attributes["Description"].Value;
                            string genre = nodeRecording.Attributes["Genre"].Value;

                            //string channelname = nodeRecording.Attributes["ChannelName"].Value;
                            string displayname = string.Empty;
                            try
                            {
                                displayname = nodeRecording.Attributes["DisplayName"].Value;
                            }
                            catch
                            {

                            }
                            Channel tmpchannel = mygetChannelbyName(displayname);
                            int idChannel = -1;
                            if (tmpchannel == null)
                            {
                                textoutput("<RED>Channel " + displayname + " (Display: " + displayname + ") not found for recording " + idRecording);
                            }
                            else
                            {
                                idChannel = tmpchannel.IdChannel;
                            }
                            string servername = nodeRecording.Attributes["ServerName"].Value;
                            Server tmpserver = mygetServerbyName(servername);
                            if (tmpserver == null)
                            {
                                textoutput("<RED>Server " + servername + " not found for recording " + idRecording);
                            }
                            int idServer = tmpserver.IdServer;
                            DateTime startTime = DateTime.ParseExact(nodeRecording.Attributes["StartTime"].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                            DateTime endTime = DateTime.ParseExact(nodeRecording.Attributes["EndTime"].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

                            //, , , episodePart
                            string episodeName = "";
                            try
                            {
                                episodeName = nodeRecording.Attributes["EpisodeName"].Value;
                            }
                            catch
                            {
                            }
                            string seriesNum = "";
                            try
                            {
                                seriesNum = nodeRecording.Attributes["SeriesNum"].Value;
                            }
                            catch
                            {
                            }
                            string episodeNum = "";
                            try
                            {
                                episodeNum = nodeRecording.Attributes["EpisodeNum"].Value;
                            }
                            catch
                            {
                            }
                            string episodePart = "";
                            try
                            {
                                episodePart = nodeRecording.Attributes["EpisodePart"].Value;
                            }
                            catch
                            {
                            }

                            DateTime keepUntilDate = DateTime.ParseExact(nodeRecording.Attributes["KeepUntilDate"].Value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                            int keepUntil = Int32.Parse(nodeRecording.Attributes["KeepUntil"].Value);
                            int timesWatched = Int32.Parse(nodeRecording.Attributes["TimesWatched"].Value);

            #if(SVN)
                                Recording recording = new Recording(idChannel, 0, false, startTime, endTime, title, description, genre, fileName, keepUntil, keepUntilDate, timesWatched, idServer, episodeName, seriesNum, episodeNum, episodePart);
                                //idChannel, idSchedule, isRecording, startTime
            #elif(MP11BETA)
                            Recording recording = new Recording(idChannel, startTime, endTime, title, description, genre, fileName, keepUntil, keepUntilDate, timesWatched, idServer, episodeName, seriesNum, episodeNum, episodePart);

            #else
                            Recording recording = new Recording(idChannel, startTime, endTime, title, description, genre, fileName, keepUntil, keepUntilDate, timesWatched, idServer);
            #endif

                                try
                                {
                                    recording.StopTime = Int32.Parse(nodeRecording.Attributes["StopTime"].Value);
                                }
                                catch
                                {
                                }
                                recording.Persist();

                                if (File.Exists(fileName) == false)
                                {
                                    textoutput("<YELLOW>Filename " + fileName + " does not exist for recording " + title + " - recording is not added to database");
                                    recording.Delete();
                                    recordingCount--;
                                }

                        }
                        catch (Exception ex)
                        {
                            recordingCount--;
                            textoutput("<RED>Could not create recording " + idRecording + " for title " + title + " and file " + fileName +  " - use \"Recording -> database ImportedFromTypeLibAttribute\" for manual import");
                            if (DEBUG)
                            {
                                textoutput("<RED>Exception message is " + ex.Message);
                            }
                            //return false;
                        }

                    }
                    textoutput(recordingCount + " recording settings imported");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_Recordings);
                }

                // Import channel groups
                if (tvgroups == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_TvGroups);
                    textoutput("Importing channel group settings");

                    XmlNodeList channelGroupList = doc.SelectNodes("/tvserver/channelgroups/channelgroup");
                    channelGroupCount = 0;
                    foreach (XmlNode nodeChannelGroup in channelGroupList)
                    {
                        int idGroup = Int32.Parse(nodeChannelGroup.Attributes["IdGroup"].Value);
                        string groupName = nodeChannelGroup.Attributes["GroupName"].Value;
                        try
                        {
                            channelGroupCount++;
                            int mapcount = 0;
                            int groupSortOrder = Int32.Parse(nodeChannelGroup.Attributes["SortOrder"].Value);
                            ChannelGroup group = layer.GetGroupByName(groupName, groupSortOrder);
                            if (group == null)
                                group = new ChannelGroup(groupName, groupSortOrder);
                            group.Persist();
                            XmlNodeList mappingList = nodeChannelGroup.SelectNodes("mappings/map");
                            foreach (XmlNode nodeMap in mappingList)
                            {
                                mapcount++;
                                //string channelname = nodeMap.Attributes["ChannelName"].Value;
                                string displayname = nodeMap.Attributes["DisplayName"].Value;
                                Channel channel = mygetChannelbyName(displayname);
                                int idMap = Int32.Parse(GetNodeAttribute(nodeMap, "IdMap", "0"));
                                int sortOrder = Int32.Parse(GetNodeAttribute(nodeMap, "SortOrder", "9999"));

                                /*
                                Log.Debug("**************************");
                                Log.Debug("group.GroupName=" + group.GroupName);
                                Log.Debug("displayname=" + displayname);
                                Log.Debug("sortOrder=" + sortOrder.ToString());
                                Log.Debug("idMap=" + idMap.ToString());*/
                                if (channel != null)
                                {

                                    //GroupMap map = new GroupMap(group.IdGroup, channel.IdChannel, sortOrder);   //!!!!!!!sortorder is overwritten when setuptv is exited
                                    //POSTIMPORT += "GROUPMAPSORTORDER\t" + group.IdGroup.ToString() + "\t" + channel.IdChannel.ToString() + "\t" + sortOrder.ToString() + "\n";

                                    GroupMap map = new GroupMap(group.IdGroup, channel.IdChannel, sortOrder);
                                    map.SortOrder = sortOrder;
                                    map.Persist();

                                    /*map.SortOrder = sortOrder;
                                    Log.Debug("map.IsPersisted=" + map.IsPersisted.ToString());
                                    map.Persist();
                                    Log.Debug("map.SortOrder=" + map.SortOrder.ToString());
                                    Log.Debug("map.IdMap=" + map.IdMap.ToString());
                                    Log.Debug("map.IsPersisted=" + map.IsPersisted.ToString());*/

                                }
                                else
                                {
                                    textoutput("<YELLOW>Channel " + displayname + " (Display: " + displayname + ") could not be assigned to group " + groupName + " in map number " + idMap);
                                }

                                Log.Debug("End");
                            }
                            textoutput(mapcount + " channels assigned to group " + groupName);
                        }
                        catch (Exception exc)
                        {
                            textoutput("<RED>TvChannels: Failed to add group " + idGroup + " group name " + groupName);
                            if (DEBUG == true)
                            {
                                textoutput("<RED>Exception message is " + exc.Message);
                            }
                            //return false;
                        }
                    }
                    textoutput(channelGroupCount + " channel group settings imported");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_TvGroups);
                }

                // Import Radio channel groups
                if (radiogroups == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_Radiogroups);
                    textoutput("Importing radio channel group settings");

                    XmlNodeList radiochannelGroupList = doc.SelectNodes("/tvserver/radiochannelgroups/radiochannelgroup");
                    radiochannelGroupCount = 0;
                    foreach (XmlNode radionodeChannelGroup in radiochannelGroupList)
                    {
                        int idGroup = Int32.Parse(radionodeChannelGroup.Attributes["IdGroup"].Value);
                        string groupName = radionodeChannelGroup.Attributes["GroupName"].Value;
                        try
                        {
                            radiochannelGroupCount++;
                            string radiogroupName = radionodeChannelGroup.Attributes["GroupName"].Value;
                            int radiogroupSortOrder = Int32.Parse(radionodeChannelGroup.Attributes["SortOrder"].Value);
                            RadioChannelGroup radiogroup = layer.GetRadioChannelGroupByName(radiogroupName);
                            if (radiogroup == null)
                                radiogroup = new RadioChannelGroup(radiogroupName, radiogroupSortOrder);
                            radiogroup.Persist();
                            XmlNodeList radiomappingList = radionodeChannelGroup.SelectNodes("mappings/radiomap");
                            int mapcount = 0;
                            foreach (XmlNode radionodeMap in radiomappingList)
                            {
                                mapcount++;
                                //string channelname = radionodeMap.Attributes["ChannelName"].Value;
                                string displayname = radionodeMap.Attributes["DisplayName"].Value;
                                Channel channel = mygetChannelbyName(displayname);

                                int sortOrder = Int32.Parse(GetNodeAttribute(radionodeMap, "SortOrder", "9999"));
                                int idMap = Int32.Parse(GetNodeAttribute(radionodeMap, "IdMap", "0"));
                                if (channel != null)
                                {
                                    RadioGroupMap radiomap = new RadioGroupMap(radiogroup.IdGroup, channel.IdChannel, sortOrder);
                                    radiomap.SortOrder = sortOrder;
                                    radiomap.Persist();
                                }
                                else
                                {
                                    textoutput("<YELLOW>Channel " + displayname + " (Display: " + displayname + ") could not be assigned to group " + radiogroupName + " in map number " + idMap);
                                }
                            }
                            textoutput(mapcount + " channels assigned to group " + groupName);
                        }
                        catch (Exception exc)
                        {
                            textoutput("<RED>RadioChannels: Failed to add radio group " + idGroup + " group name " + groupName);
                            if (DEBUG == true)
                            {
                                textoutput("<RED>Exception message is " + exc.Message);
                            }
                            //return false;
                        }
                    }
                    textoutput(radiochannelGroupCount + " radio channel group settings imported");
                    progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_Radiogroups);
                }

                if (general_settings == true)
                {
                    // import all settings
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_GeneralSettings);
                    textoutput("Importing TV server settings");

                    int ctr = 0;
                    XmlNodeList nodesettings = doc.SelectNodes("/tvserver/AllSettings/Setting");
                    foreach (XmlNode nodesetting in nodesettings)
                    {
                        XmlAttributeCollection allattributes = nodesetting.Attributes;
                        try
                        {
                            string myattribute = allattributes[0].Name.Replace("__SPACE__", " "); //reconverting attributes from export - do not change
                            myattribute = myattribute.Replace("__PLUS__", "+"); //reconverting attributes from export - do not change

                            if (DEBUG)
                                textoutput("Attribute: " + myattribute + "    Value=" + allattributes[0].Value);

                            PostImport(doc, nodesetting, myattribute);
                            ctr++;

                        }
                        catch
                        {
                            textoutput("<RED>Error reading attribute");
                        }
                    }

                    textoutput(ctr.ToString() + " settings imported");

                }

                if (clickfinder == true)
                {
                    progressbar((int)PB_action.START, ref PB_Import, (int)PB_part.TV_PluginSettings);

                    string plugversion = detectplugin("TV Movie EPG import");
                    if (plugversion != "NOT_FOUND")
                    {

                        textoutput("Importing TV movie");

                        //TVMovie mappings
                        textoutput("Delete old TV movie mappings");

                        tvmovieCount = 0;
            #if(MP100)
                        IList mappingDb = TvMovieMapping.ListAll();
            #elif(MP101)
                        IList<TvMovieMapping> mappingDb = TvMovieMapping.ListAll();
            #else //MP11BETA or SVN
                        IList<TvMovieMapping> mappingDb = TvMovieMapping.ListAll();
            #endif

                        if (mappingDb != null)
                        {
                            if (mappingDb.Count > 0)
                            {
                                foreach (TvMovieMapping mapping in mappingDb)
                                {
                                    tvmovieCount++;
                                    mapping.Remove();

                                }
                            }
                        }
                        textoutput(tvmovieCount + " TV movie mappings deleted");

                        layer = new TvBusinessLayer();

                        textoutput("Importing TV movie mappings");

                        XmlNodeList tvmoviemapping = doc.SelectNodes("/tvserver/TVMovieMappings/TVMovieMapping");
                        tvmovieCount = 0;

                        foreach (XmlNode nodetvmoviemapping in tvmoviemapping)
                        {

                            string dpname = nodetvmoviemapping.Attributes["MPDisplayName"].Value;
                            try
                            {

                                if (DEBUG)
                                {
                                    textoutput("TvMovie mappings: Display ="+ dpname);
                                }
                                //Channel channel = layer.GetChannelByName(chname);

                                Channel channel = mygetChannelbyName(dpname);

                                if (channel == null)
                                {
                                    textoutput("<YELLOW>TV movie EPG mapping failed  (Display: " + dpname + ") was not found");

                                }
                                else
                                {
                                    int idChannel = channel.IdChannel;
                                    string stationName = nodetvmoviemapping.Attributes["StationName"].Value;
                                    string timeSharingStart = nodetvmoviemapping.Attributes["TimeSharingStart"].Value;
                                    string timeSharingEnd = nodetvmoviemapping.Attributes["TimeSharingEnd"].Value;
                                    //TvMovieMapping tvmapping = new TvMovieMapping(idChannel, stationName, timeSharingStart, timeSharingEnd);
                                    //tvmapping.Persist();
                                    tvmovieCount++;
                                    POSTIMPORT += "TVMOVIE\t" + idChannel + "\t" + stationName + "\t" + timeSharingStart + "\t" + timeSharingEnd + "\n";
                                }
                            }
                            catch (Exception exc)
                            {
                                textoutput("<RED>Tv movie mappings: Failed to add mapping for channel  (Display:" + dpname + ") ");
                                if (DEBUG == true)
                                {
                                    textoutput("<RED>Exception message is " + exc.Message);
                                }
                                return false;
                            }
                        }
                        textoutput(tvmovieCount + " TV movie mappings imported");

                    }

                }
                textoutput("TV server import finished");
                progressbar((int)PB_action.STOP, ref PB_Import, (int)PB_part.TV_PluginSettings);

            }
            catch (Exception ex)
            {
                textoutput("<RED>Error while importing:" + ex.ToString() + " " + ex.StackTrace);
                myMessageBox("Error while importing:\n\n" + ex.ToString() + " " + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

                return false;
            }

            return true;
        }
Esempio n. 8
0
    private void importButton_Click(object sender, EventArgs e)
    {
      bool importtv = imCheckTvChannels.Checked;
      bool importtvgroups = imCheckTvGroups.Checked;
      bool importradio = imCheckRadioChannels.Checked;
      bool importradiogroups = imCheckRadioGroups.Checked;
      bool importschedules = imCheckSchedules.Checked;

      openFileDialog1.CheckFileExists = true;
      openFileDialog1.DefaultExt = "xml";
      openFileDialog1.RestoreDirectory = true;
      openFileDialog1.Title = "Load channels, channel groups and schedules";
      openFileDialog1.InitialDirectory = String.Format(@"{0}\Team MediaPortal\MediaPortal TV Server",
                                                       Environment.GetFolderPath(
                                                         Environment.SpecialFolder.CommonApplicationData));
      openFileDialog1.FileName = "export.xml";
      openFileDialog1.AddExtension = true;
      openFileDialog1.Multiselect = false;
      if (openFileDialog1.ShowDialog(this) != DialogResult.OK)
        return;
      NotifyForm dlg = new NotifyForm("Importing tv channels...", "This can take some time\n\nPlease be patient...");
      try
      {
        dlg.Show();
        dlg.WaitForDisplay();
        CountryCollection collection = new CountryCollection();
        TvBusinessLayer layer = new TvBusinessLayer();
        bool mergeChannels = false; // every exported channel will be imported on its own.
        int channelCount = 0;
        int scheduleCount = 0;
        int tvChannelGroupCount = 0;
        int radioChannelGroupCount = 0;

        if (layer.Channels.Count > 0 && (importtv || importradio))
        {
          // rtv: we could offer to set a "merge" property here so tuningdetails would be updated for existing channels.
          if (
            MessageBox.Show(
              "Existing channels detected! \nIf you continue to import your old backup then all identically named channels will be treated equal - there is a risk of duplicate entries. \nDo you really want to go on?",
              "Channels found", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.Cancel)
            return;
          else
            mergeChannels = true;
        }

        XmlDocument doc = new XmlDocument();
        Log.Info("TvChannels: Trying to import channels from {0}", openFileDialog1.FileName);
        doc.Load(openFileDialog1.FileName);
        XmlNodeList channelList = doc.SelectNodes("/tvserver/channels/channel");
        XmlNodeList tvChannelGroupList = doc.SelectNodes("/tvserver/channelgroups/channelgroup");
        XmlNodeList radioChannelGroupList = doc.SelectNodes("/tvserver/radiochannelgroups/radiochannelgroup");
        XmlNodeList scheduleList = doc.SelectNodes("/tvserver/schedules/schedule");
        if (channelList != null)
        {
          foreach (XmlNode nodeChannel in channelList)
          {
            try
            {
              Channel dbChannel;
              XmlNodeList tuningList = nodeChannel.SelectNodes("TuningDetails/tune");
              XmlNodeList mappingList = nodeChannel.SelectNodes("mappings/map");
              bool grabEpg = (GetNodeAttribute(nodeChannel, "GrabEpg", "True") == "True");
              bool isRadio = (GetNodeAttribute(nodeChannel, "IsRadio", "False") == "True");
              bool isTv = (GetNodeAttribute(nodeChannel, "IsTv", "True") == "True");
              DateTime lastGrabTime = DateTime.ParseExact(GetNodeAttribute(nodeChannel, "LastGrabTime", "01.01.1900"),
                                                          "yyyy-M-d H:m:s", CultureInfo.InvariantCulture);
              int sortOrder = Int32.Parse(GetNodeAttribute(nodeChannel, "SortOrder", "0"));
              int timesWatched = Int32.Parse(GetNodeAttribute(nodeChannel, "TimesWatched", "0"));
              DateTime totalTimeWatched =
                DateTime.ParseExact(GetNodeAttribute(nodeChannel, "TotalTimeWatched", "01.01.1900"), "yyyy-M-d H:m:s",
                                    CultureInfo.InvariantCulture);
              bool visibileInGuide = (GetNodeAttribute(nodeChannel, "VisibleInGuide", "True") == "True");
              bool FreeToAir = (GetNodeAttribute(nodeChannel, "FreeToAir", "True") == "True");
              string displayName = GetNodeAttribute(nodeChannel, "DisplayName", "Unkown");
              int chChannelNumber = Int32.Parse(GetNodeAttribute(nodeChannel, "ChannelNumber", "10000"));

              // Only import TV or radio channels if the corresponding checkbox was checked
              if ((isTv && !importtv) || (isRadio && !importradio))
                continue;

              channelCount++;

              // rtv: since analog allows NOT to merge channels we need to take care of this. US users e.g. have multiple stations named "Sport" with different tuningdetails.
              // using AddChannel would incorrectly "merge" these totally different channels.
              // see this: http://forum.team-mediaportal.com/1-0-rc1-svn-builds-271/importing-exported-channel-list-groups-channels-39368/
              Log.Info("TvChannels: Adding {0}. channel: {1}", channelCount, displayName);
              IList<Channel> foundExistingChannels = layer.GetChannelsByName(displayName);
              if (mergeChannels && (foundExistingChannels != null && foundExistingChannels.Count > 0))
              {
                dbChannel = foundExistingChannels[0];
              }
              else
              {
                dbChannel = layer.AddNewChannel(displayName, chChannelNumber);
              }

              dbChannel.GrabEpg = grabEpg;
              dbChannel.IsRadio = isRadio;
              dbChannel.IsTv = isTv;
              dbChannel.LastGrabTime = lastGrabTime;
              dbChannel.SortOrder = sortOrder;
              dbChannel.TimesWatched = timesWatched;
              dbChannel.TotalTimeWatched = totalTimeWatched;
              dbChannel.VisibleInGuide = visibileInGuide;
              dbChannel.DisplayName = displayName;
              dbChannel.Persist();

              //
              // chemelli: When we import channels we need to add those to the "AllChannels" group
              //
              if (isTv)
              {
                layer.AddChannelToGroup(dbChannel, TvConstants.TvGroupNames.AllChannels);
              }
              else
              {
                layer.AddChannelToRadioGroup(dbChannel, TvConstants.RadioGroupNames.AllChannels);
              }

              foreach (XmlNode nodeMap in mappingList)
              {
                int idCard = Int32.Parse(nodeMap.Attributes["IdCard"].Value);
                XmlNode nodeCard =
                  doc.SelectSingleNode(String.Format("/tvserver/servers/server/cards/card[@IdCard={0}]", idCard));
                Card dbCard = layer.GetCardByDevicePath(nodeCard.Attributes["DevicePath"].Value);
                if (dbCard != null)
                {
                  layer.MapChannelToCard(dbCard, dbChannel, false);
                }
              }
              foreach (XmlNode nodeTune in tuningList)
              {
                int bandwidth = Int32.Parse(nodeTune.Attributes["Bandwidth"].Value);
                int channelNumber = Int32.Parse(nodeTune.Attributes["ChannelNumber"].Value);
                int channelType = Int32.Parse(nodeTune.Attributes["ChannelType"].Value);
                int countryId = Int32.Parse(nodeTune.Attributes["CountryId"].Value);
                int diseqc = Int32.Parse(nodeTune.Attributes["Diseqc"].Value);
                bool fta = (nodeTune.Attributes["FreeToAir"].Value == "True");
                int frequency = Int32.Parse(nodeTune.Attributes["Frequency"].Value);
                int majorChannel = Int32.Parse(nodeTune.Attributes["MajorChannel"].Value);
                int minorChannel = Int32.Parse(nodeTune.Attributes["MinorChannel"].Value);
                int modulation = Int32.Parse(nodeTune.Attributes["Modulation"].Value);
                string name = nodeTune.Attributes["Name"].Value;
                int networkId = Int32.Parse(nodeTune.Attributes["NetworkId"].Value);
                int pmtPid = Int32.Parse(nodeTune.Attributes["PmtPid"].Value);
                int polarisation = Int32.Parse(nodeTune.Attributes["Polarisation"].Value);
                string provider = GetNodeAttribute(nodeTune, "Provider", "");
                int serviceId = Int32.Parse(nodeTune.Attributes["ServiceId"].Value);
                int switchingFrequency = Int32.Parse(nodeTune.Attributes["SwitchingFrequency"].Value);
                int symbolrate = Int32.Parse(nodeTune.Attributes["Symbolrate"].Value);
                int transportId = Int32.Parse(nodeTune.Attributes["TransportId"].Value);
                int tuningSource = Int32.Parse(GetNodeAttribute(nodeTune, "TuningSource", "0"));
                int videoSource = Int32.Parse(GetNodeAttribute(nodeTune, "VideoSource", "0"));
                int audioSource = Int32.Parse(GetNodeAttribute(nodeTune, "AudioSource", "0"));
                bool isVCRSignal = (GetNodeAttribute(nodeChannel, "IsVCRSignal", "False") == "True");
                int SatIndex = Int32.Parse(GetNodeAttribute(nodeTune, "SatIndex", "-1"));
                int InnerFecRate = Int32.Parse(GetNodeAttribute(nodeTune, "InnerFecRate", "-1"));
                int band = Int32.Parse(GetNodeAttribute(nodeTune, "Band", "0"));
                int pilot = Int32.Parse(GetNodeAttribute(nodeTune, "Pilot", "-1"));
                int rollOff = Int32.Parse(GetNodeAttribute(nodeTune, "RollOff", "-1"));
                string url = GetNodeAttribute(nodeTune, "Url", "");
                int bitrate = Int32.Parse(GetNodeAttribute(nodeTune, "Bitrate", "0"));

                switch (channelType)
                {
                  case 0: //AnalogChannel
                    AnalogChannel analogChannel = new AnalogChannel();
                    analogChannel.ChannelNumber = channelNumber;
                    analogChannel.Country = collection.Countries[countryId];
                    analogChannel.Frequency = frequency;
                    analogChannel.IsRadio = isRadio;
                    analogChannel.IsTv = isTv;
                    analogChannel.Name = name;
                    analogChannel.TunerSource = (TunerInputType)tuningSource;
                    analogChannel.AudioSource = (AnalogChannel.AudioInputType)audioSource;
                    analogChannel.VideoSource = (AnalogChannel.VideoInputType)videoSource;
                    analogChannel.IsVCRSignal = isVCRSignal;
                    layer.AddTuningDetails(dbChannel, analogChannel);
                    Log.Info("TvChannels: Added tuning details for analog channel: {0} number: {1}", name, channelNumber);
                    break;
                  case 1: //ATSCChannel
                    ATSCChannel atscChannel = new ATSCChannel();
                    atscChannel.MajorChannel = majorChannel;
                    atscChannel.MinorChannel = minorChannel;
                    atscChannel.PhysicalChannel = channelNumber;
                    atscChannel.FreeToAir = fta;
                    atscChannel.Frequency = frequency;
                    atscChannel.IsRadio = isRadio;
                    atscChannel.IsTv = isTv;
                    atscChannel.Name = name;
                    atscChannel.NetworkId = networkId;
                    atscChannel.PmtPid = pmtPid;
                    atscChannel.Provider = provider;
                    atscChannel.ServiceId = serviceId;
                    atscChannel.TransportId = transportId;
                    atscChannel.ModulationType = (ModulationType)modulation;
                    layer.AddTuningDetails(dbChannel, atscChannel);
                    Log.Info("TvChannels: Added tuning details for ATSC channel: {0} number: {1} provider: {2}", name,
                             channelNumber, provider);
                    break;
                  case 2: //DVBCChannel
                    DVBCChannel dvbcChannel = new DVBCChannel();
                    dvbcChannel.ModulationType = (ModulationType)modulation;
                    dvbcChannel.FreeToAir = fta;
                    dvbcChannel.Frequency = frequency;
                    dvbcChannel.IsRadio = isRadio;
                    dvbcChannel.IsTv = isTv;
                    dvbcChannel.Name = name;
                    dvbcChannel.NetworkId = networkId;
                    dvbcChannel.PmtPid = pmtPid;
                    dvbcChannel.Provider = provider;
                    dvbcChannel.ServiceId = serviceId;
                    dvbcChannel.SymbolRate = symbolrate;
                    dvbcChannel.TransportId = transportId;
                    dvbcChannel.LogicalChannelNumber = channelNumber;
                    layer.AddTuningDetails(dbChannel, dvbcChannel);
                    Log.Info("TvChannels: Added tuning details for DVB-C channel: {0} provider: {1}", name, provider);
                    break;
                  case 3: //DVBSChannel
                    DVBSChannel dvbsChannel = new DVBSChannel();
                    dvbsChannel.DisEqc = (DisEqcType)diseqc;
                    dvbsChannel.Polarisation = (Polarisation)polarisation;
                    dvbsChannel.SwitchingFrequency = switchingFrequency;
                    dvbsChannel.FreeToAir = fta;
                    dvbsChannel.Frequency = frequency;
                    dvbsChannel.IsRadio = isRadio;
                    dvbsChannel.IsTv = isTv;
                    dvbsChannel.Name = name;
                    dvbsChannel.NetworkId = networkId;
                    dvbsChannel.PmtPid = pmtPid;
                    dvbsChannel.Provider = provider;
                    dvbsChannel.ServiceId = serviceId;
                    dvbsChannel.SymbolRate = symbolrate;
                    dvbsChannel.TransportId = transportId;
                    dvbsChannel.SatelliteIndex = SatIndex;
                    dvbsChannel.ModulationType = (ModulationType)modulation;
                    dvbsChannel.InnerFecRate = (BinaryConvolutionCodeRate)InnerFecRate;
                    dvbsChannel.BandType = (BandType)band;
                    dvbsChannel.Pilot = (Pilot)pilot;
                    dvbsChannel.Rolloff = (RollOff)rollOff;
                    dvbsChannel.LogicalChannelNumber = channelNumber;
                    layer.AddTuningDetails(dbChannel, dvbsChannel);
                    Log.Info("TvChannels: Added tuning details for DVB-S channel: {0} provider: {1}", name, provider);
                    break;
                  case 4: //DVBTChannel
                    DVBTChannel dvbtChannel = new DVBTChannel();
                    dvbtChannel.BandWidth = bandwidth;
                    dvbtChannel.FreeToAir = fta;
                    dvbtChannel.Frequency = frequency;
                    dvbtChannel.IsRadio = isRadio;
                    dvbtChannel.IsTv = isTv;
                    dvbtChannel.Name = name;
                    dvbtChannel.NetworkId = networkId;
                    dvbtChannel.PmtPid = pmtPid;
                    dvbtChannel.Provider = provider;
                    dvbtChannel.ServiceId = serviceId;
                    dvbtChannel.TransportId = transportId;
                    dvbtChannel.LogicalChannelNumber = channelNumber;
                    layer.AddTuningDetails(dbChannel, dvbtChannel);
                    Log.Info("TvChannels: Added tuning details for DVB-T channel: {0} provider: {1}", name, provider);
                    break;
                  case 5: //Webstream
                    layer.AddWebStreamTuningDetails(dbChannel, url, bitrate);
                    break;
                  case 7: //DVBIPChannel
                    DVBIPChannel dvbipChannel = new DVBIPChannel();
                    dvbipChannel.FreeToAir = fta;
                    dvbipChannel.Frequency = frequency;
                    dvbipChannel.IsRadio = isRadio;
                    dvbipChannel.IsTv = isTv;
                    dvbipChannel.LogicalChannelNumber = channelNumber;
                    dvbipChannel.Name = name;
                    dvbipChannel.NetworkId = networkId;
                    dvbipChannel.PmtPid = pmtPid;
                    dvbipChannel.Provider = provider;
                    dvbipChannel.ServiceId = serviceId;
                    dvbipChannel.TransportId = transportId;
                    dvbipChannel.Url = url;
                    layer.AddTuningDetails(dbChannel, dvbipChannel);
                    Log.Info("TvChannels: Added tuning details for DVB-IP channel: {0} provider: {1}", name, provider);
                    break;
                }
              }
            }
            catch (Exception exc)
            {
              Log.Error("TvChannels: Failed to add channel - {0}", exc.Message);
            }
          }
        }

        if (tvChannelGroupList != null && importtvgroups)
        {
          // Import tv channel groups
          foreach (XmlNode nodeChannelGroup in tvChannelGroupList)
          {
            try
            {
              tvChannelGroupCount++;
              string groupName = nodeChannelGroup.Attributes["GroupName"].Value;
              int groupSortOrder = Int32.Parse(nodeChannelGroup.Attributes["SortOrder"].Value);
              ChannelGroup group = null;
              if (groupName == TvConstants.TvGroupNames.AllChannels)
              {
                group = layer.GetGroupByName(groupName) ??
                        new ChannelGroup(groupName, groupSortOrder);
              }
              else
              {
                group = layer.GetGroupByName(groupName, groupSortOrder) ??
                        new ChannelGroup(groupName, groupSortOrder);
              }
              group.Persist();
              XmlNodeList mappingList = nodeChannelGroup.SelectNodes("mappings/map");
              foreach (XmlNode nodeMap in mappingList)
              {
                IList<Channel> channels = layer.GetChannelsByName(nodeMap.Attributes["ChannelName"].Value);
                int sortOrder = Int32.Parse(GetNodeAttribute(nodeMap, "SortOrder", "9999"));
                if (channels != null && channels.Count > 0)
                {
                  Channel channel = channels[0];
                  if (!channel.GroupNames.Contains(group.GroupName))
                  {
                    GroupMap map = new GroupMap(group.IdGroup, channel.IdChannel, sortOrder);
                    map.Persist();
                  }
                  else
                  {
                    foreach (GroupMap map in channel.ReferringGroupMap())
                    {
                      if (map.IdGroup == group.IdGroup)
                      {
                        map.SortOrder = sortOrder;
                        map.Persist();
                        break;
                      }
                    }
                  }
                }
              }
            }
            catch (Exception exg)
            {
              Log.Error("TvChannels: Failed to add group - {0}", exg.Message);
            }
          }
        }

        if (radioChannelGroupList != null && importradiogroups)
        {
          // Import radio channel groups
          foreach (XmlNode nodeChannelGroup in radioChannelGroupList)
          {
            try
            {
              radioChannelGroupCount++;
              string groupName = nodeChannelGroup.Attributes["GroupName"].Value;
              int groupSortOrder = Int32.Parse(nodeChannelGroup.Attributes["SortOrder"].Value);
              RadioChannelGroup group = layer.GetRadioChannelGroupByName(groupName) ??
                                        new RadioChannelGroup(groupName, groupSortOrder);
              group.Persist();
              XmlNodeList mappingList = nodeChannelGroup.SelectNodes("mappings/map");
              foreach (XmlNode nodeMap in mappingList)
              {
                IList<Channel> channels = layer.GetChannelsByName(nodeMap.Attributes["ChannelName"].Value);
                int sortOrder = Int32.Parse(GetNodeAttribute(nodeMap, "SortOrder", "9999"));
                if (channels != null && channels.Count > 0)
                {
                  Channel channel = channels[0];
                  if (!channel.GroupNames.Contains(group.GroupName))
                  {
                    RadioGroupMap map = new RadioGroupMap(group.IdGroup, channel.IdChannel, sortOrder);
                    map.Persist();
                  }
                  else
                  {
                    foreach (RadioGroupMap map in channel.ReferringRadioGroupMap())
                    {
                      if (map.IdGroup == group.IdGroup)
                      {
                        map.SortOrder = sortOrder;
                        map.Persist();
                        break;
                      }
                    }
                  }
                }
              }
            }
            catch (Exception exg)
            {
              Log.Error("Radio Channels: Failed to add group - {0}", exg.Message);
            }
          }
        }

        if (scheduleList != null && importschedules)
        {
          // Import schedules
          foreach (XmlNode nodeSchedule in scheduleList)
          {
            try
            {
              int idChannel = -1;

              string programName = nodeSchedule.Attributes["ProgramName"].Value;
              string channel = nodeSchedule.Attributes["ChannelName"].Value;
              if (!string.IsNullOrEmpty(channel))
              {
                IList<Channel> channels = layer.GetChannelsByName(channel);
                if (channels != null && channels.Count > 0)
                {
                  idChannel = channels[0].IdChannel;
                }
              }
              DateTime startTime = DateTime.ParseExact(nodeSchedule.Attributes["StartTime"].Value, "yyyy-M-d H:m:s",
                                                       CultureInfo.InvariantCulture);
              DateTime endTime = DateTime.ParseExact(nodeSchedule.Attributes["EndTime"].Value, "yyyy-M-d H:m:s",
                                                     CultureInfo.InvariantCulture);
              int scheduleType = Int32.Parse(nodeSchedule.Attributes["ScheduleType"].Value);
              Schedule schedule = layer.AddSchedule(idChannel, programName, startTime, endTime, scheduleType);

              schedule.ScheduleType = scheduleType;
              schedule.KeepDate = DateTime.ParseExact(nodeSchedule.Attributes["KeepDate"].Value, "yyyy-M-d H:m:s",
                                                      CultureInfo.InvariantCulture);
              schedule.PreRecordInterval = Int32.Parse(nodeSchedule.Attributes["PreRecordInterval"].Value);
              schedule.PostRecordInterval = Int32.Parse(nodeSchedule.Attributes["PostRecordInterval"].Value);
              schedule.Priority = Int32.Parse(nodeSchedule.Attributes["Priority"].Value);
              schedule.Quality = Int32.Parse(nodeSchedule.Attributes["Quality"].Value);
              schedule.Directory = nodeSchedule.Attributes["Directory"].Value;
              schedule.KeepMethod = Int32.Parse(nodeSchedule.Attributes["KeepMethod"].Value);
              schedule.MaxAirings = Int32.Parse(nodeSchedule.Attributes["MaxAirings"].Value);              
              schedule.ScheduleType = Int32.Parse(nodeSchedule.Attributes["ScheduleType"].Value);
              schedule.Series = (GetNodeAttribute(nodeSchedule, "Series", "False") == "True");
              if (idChannel > -1)
              {
                schedule.Persist();
                scheduleCount++;
                Log.Info("TvChannels: Added schedule: {0} on channel: {1}", programName, channel);
              }
              else
                Log.Info("TvChannels: Skipped schedule: {0} because the channel was unknown: {1}", programName, channel);
            }
            catch (Exception ex)
            {
              Log.Error("TvChannels: Failed to add schedule - {0}", ex.Message);
            }
          }
        }

        dlg.Close();
        Log.Info(
          "TvChannels: Imported {0} channels, {1} tv channel groups, {2} radio channel groups and {3} schedules",
          channelCount, tvChannelGroupCount, radioChannelGroupCount, scheduleCount);
        MessageBox.Show(
          String.Format("Imported {0} channels, {1} tv channel groups, {2} radio channel groups and {3} schedules",
                        channelCount, tvChannelGroupCount, radioChannelGroupCount, scheduleCount));
      }
      catch (Exception ex)
      {
        MessageBox.Show(this, "Error while importing:\n\n" + ex + " " + ex.StackTrace);
      }
      finally
      {
        dlg.Close();
        OnSectionActivated();
      }
    }
Esempio n. 9
0
    /// <summary>
    /// Sets the DVB-S2 parameters such as modulation, roll-off, pilot etc.
    /// </summary>
    /// <param name="parameters">The LNB parameters.</param>
    /// <param name="channel">The channel to tune.</param>
    /// <returns>The channel with DVB-S2 parameters set.</returns>
    public DVBSChannel SetDVBS2Modulation(ScanParameters parameters, DVBSChannel channel)
    {
      //Log.Log.WriteFile("Trying to set DVB-S2 modulation...");
      try
      {
        if (_twinhan != null)
        {
          //DVB-S2 modulation parameters for Twinhan
          if (channel.ModulationType == ModulationType.ModQpsk)
          {
            channel.ModulationType = ModulationType.Mod8Vsb;
          }
          if (channel.ModulationType == ModulationType.Mod8Psk)
          {
            channel.ModulationType = ModulationType.Mod8Vsb;
          }
          if (channel.ModulationType == ModulationType.Mod16Apsk)
          {
            channel.ModulationType = ModulationType.Mod16Vsb;
          }
          if (channel.ModulationType == ModulationType.Mod32Apsk)
          {
            channel.ModulationType = ModulationType.ModOqpsk;
          }
          Log.Log.WriteFile("Twinhan DVB-S2 modulation set to:{0}", channel.ModulationType);
          Log.Log.WriteFile("Twinhan DVB-S2 Pilot set to:{0}", channel.Pilot);
          Log.Log.WriteFile("Twinhan DVB-S2 RollOff set to:{0}", channel.Rolloff);
          Log.Log.WriteFile("Twinhan DVB-S2 fec set to:{0}", channel.InnerFecRate);
          return channel;
        }
        if (_hauppauge != null)
        {
          //Set Hauppauge pilot, roll-off settings but only if DVB-S2
          //We assume if the modulation is set then a DVB-S2 tuning request has been requested
          if (channel.ModulationType != ModulationType.ModNotSet)
          {
            //Set the alternative Hauppauge Modulation type
            if (channel.ModulationType == ModulationType.ModQpsk)
            {
              if (channel.InnerFecRate == BinaryConvolutionCodeRate.Rate9_10)
              {
                channel.ModulationType = ModulationType.Mod32Qam;
              }
              channel.ModulationType = channel.InnerFecRate == BinaryConvolutionCodeRate.Rate8_9
                                         ? ModulationType.Mod16Qam
                                         : ModulationType.ModBpsk;
            }
            //Set the Hauppauge Modulation type
            /*if (channel.ModulationType == ModulationType.ModQpsk)
            {
              channel.ModulationType = ModulationType.ModQpsk2;
            }*/
            if (channel.ModulationType == ModulationType.Mod8Psk)
            {
              channel.ModulationType = ModulationType.ModNbc8Psk;
            }
            if (channel.SymbolRate == 30000)
            {
              channel.Pilot = Pilot.Off;
            }
            Log.Log.WriteFile("Hauppauge DVB-S2 modulation set to:{0}", channel.ModulationType);
            Log.Log.WriteFile("Hauppauge DVB-S2 Pilot set to:{0}", channel.Pilot);
            Log.Log.WriteFile("Hauppauge DVB-S2 RollOff set to:{0}", channel.Rolloff);
            Log.Log.WriteFile("Hauppauge DVB-S2 fec set to:{0}", channel.InnerFecRate);
            _hauppauge.SetDVBS2PilotRolloff(channel);
          }
          return channel;
        }
        if (_profred != null)
        {
          //Set ProfRed pilot, roll-off settings
          if (channel.ModulationType == ModulationType.ModNotSet)
          {
            channel.ModulationType = ModulationType.ModNotDefined;
          }
          if (channel.ModulationType == ModulationType.Mod8Psk)
          {
            channel.ModulationType = ModulationType.ModBpsk;
          }
          Log.Log.WriteFile("ProfRed DVB-S2 modulation set to:{0}", channel.ModulationType);
          Log.Log.WriteFile("ProfRed DVB-S2 Pilot set to:{0}", channel.Pilot);
          Log.Log.WriteFile("ProfRed DVB-S2 RollOff set to:{0}", channel.Rolloff);
          Log.Log.WriteFile("ProfRed DVB-S2 fec set to:{0}", channel.InnerFecRate);
          //}
          return channel;
        }
        if (_technoTrend != null)
        {
          //Set TechnoTrend modulation tuning settings
          if (channel.ModulationType == ModulationType.ModQpsk)
          {
            channel.ModulationType = ModulationType.Mod8Vsb;
          }
          if (channel.ModulationType == ModulationType.Mod8Psk)
          {
            channel.ModulationType = ModulationType.Mod8Vsb;
          }
          if (channel.ModulationType == ModulationType.Mod16Apsk)
          {
            channel.ModulationType = ModulationType.Mod16Vsb;
          }
          if (channel.ModulationType == ModulationType.Mod32Apsk)
          {
            channel.ModulationType = ModulationType.ModOqpsk;
          }
          Log.Log.WriteFile("Technotrend DVB-S2 modulation set to:{0}", channel.ModulationType);
          Log.Log.WriteFile("Technotrend DVB-S2 Pilot set to:{0}", channel.Pilot);
          Log.Log.WriteFile("Technotrend DVB-S2 RollOff set to:{0}", channel.Rolloff);
          Log.Log.WriteFile("Technotrend DVB-S2 fec set to:{0}", channel.InnerFecRate);
          return channel;
        }
        if (_knc != null)
        {
          //Set KNC modulation tuning settings
          if (channel.ModulationType == ModulationType.ModQpsk)
          {
            channel.ModulationType = ModulationType.Mod8Vsb;
          }
          if (channel.ModulationType == ModulationType.Mod8Psk)
          {
            channel.ModulationType = ModulationType.Mod8Vsb;
          }
          if (channel.ModulationType == ModulationType.Mod16Apsk)
          {
            channel.ModulationType = ModulationType.Mod16Vsb;
          }
          if (channel.ModulationType == ModulationType.Mod32Apsk)
          {
            channel.ModulationType = ModulationType.ModOqpsk;
          }
          Log.Log.WriteFile("KNC DVB-S2 modulation set to:{0}", channel.ModulationType);
          Log.Log.WriteFile("KNC DVB-S2 Pilot set to:{0}", channel.Pilot);
          Log.Log.WriteFile("KNC DVB-S2 RollOff set to:{0}", channel.Rolloff);
          Log.Log.WriteFile("KNC DVB-S2 fec set to:{0}", channel.InnerFecRate);
          return channel;
        }
        if (_digitalEveryWhere != null)
        {
          if (channel.ModulationType == ModulationType.ModQpsk)
          {
            channel.ModulationType = ModulationType.ModNbcQpsk;
          }
          if (channel.ModulationType == ModulationType.Mod8Psk)
          {
            channel.ModulationType = ModulationType.ModNbc8Psk;
          }
          //Check if DVB-S channel if not turn off Pilot & Roll-off regardless
          if (channel.ModulationType == ModulationType.ModNotSet)
          {
            channel.Pilot = Pilot.NotSet;
            channel.Rolloff = RollOff.NotSet;
            //Log.Log.WriteFile("DigitalEverywhere: we're tuning DVB-S, pilot & roll-off are now not set");
          }

          if (channel.InnerFecRate != BinaryConvolutionCodeRate.RateNotSet)
          {
            //Set the DigitalEverywhere binary values for Pilot & Roll-off
            int _pilot = 0;
            int _rollOff = 0;
            if (channel.Pilot == Pilot.On)
              _pilot = 128;
            if (channel.Pilot == Pilot.Off)
              _pilot = 64;
            if (channel.Rolloff == RollOff.Twenty)
              _rollOff = 16;
            if (channel.Rolloff == RollOff.TwentyFive)
              _rollOff = 32;
            if (channel.Rolloff == RollOff.ThirtyFive)
              _rollOff = 48;
            //The binary values get added to the current InnerFECRate - done!
            BinaryConvolutionCodeRate r = channel.InnerFecRate + _pilot + _rollOff;
            channel.InnerFecRate = r;
          }
          Log.Log.WriteFile("DigitalEverywhere DVB-S2 modulation set to:{0}", channel.ModulationType);
          Log.Log.WriteFile("DigitalEverywhere Pilot set to:{0}", channel.Pilot);
          Log.Log.WriteFile("DigitalEverywhere RollOff set to:{0}", channel.Rolloff);
          Log.Log.WriteFile("DigitalEverywhere fec set to:{0}", (int)channel.InnerFecRate);
          return channel;
        }
      }
      catch (Exception ex)
      {
        Log.Log.Write(ex);
      }
      return channel;
    }
Esempio n. 10
0
 /// <summary>
 /// Sets the DVB s2 modulation.
 /// </summary>
 /// <param name="parameters">The parameters.</param>
 /// <param name="channel">The channel.</param>
 public DVBSChannel SetDVBS2Modulation(ScanParameters parameters, DVBSChannel channel)
 {
   return channel;
 }
Esempio n. 11
0
 /// <summary>
 /// Sends the diseq command.
 /// </summary>
 /// <param name="parameters">Scan parameters</param>
 /// <param name="channel">The channel.</param>
 public void SendDiseqCommand(ScanParameters parameters, DVBSChannel channel)
 {
   byte disEqcPort = (byte)BandTypeConverter.GetAntennaNr(channel);
   Int32 LNBLOFLowBand;
   Int32 LNBLOFHighBand;
   Int32 LNBLOFHiLoSW;
   BandTypeConverter.GetDefaultLnbSetup(parameters, channel.BandType, out LNBLOFLowBand, out LNBLOFHighBand,
                                        out LNBLOFHiLoSW);
   byte turnon22Khz = BandTypeConverter.IsHiBand(channel, parameters) ? (byte)2 : (byte)1;
   SetLnbData(true, LNBLOFLowBand, LNBLOFHighBand, LNBLOFHiLoSW, turnon22Khz, disEqcPort);
   SendDiseqcCommandTest(parameters, channel);
 }
Esempio n. 12
0
 /// <summary>
 /// checks if a received EPGChannel should be filtered from the resultlist
 /// </summary>
 /// <value></value>
 protected override bool FilterOutEPGChannel(EpgChannel epgChannel)
 {
   TvBusinessLayer layer = new TvBusinessLayer();
   if (layer.GetSetting("generalGrapOnlyForSameTransponder", "no").Value == "yes")
   {
     DVBBaseChannel chan = epgChannel.Channel as DVBBaseChannel;
     Channel dbchannel = layer.GetChannelByTuningDetail(chan.NetworkId, chan.TransportId, chan.ServiceId);
     DVBSChannel dvbschannel = new DVBSChannel();
     if (dbchannel == null)
     {
       return false;
     }
     foreach (TuningDetail detail in dbchannel.ReferringTuningDetail())
     {
       if (detail.ChannelType == 3)
       {
         dvbschannel.Frequency = detail.Frequency;
         dvbschannel.Polarisation = (Polarisation)detail.Polarisation;
         dvbschannel.ModulationType = (ModulationType)detail.Modulation;
         dvbschannel.SatelliteIndex = detail.SatIndex;
         dvbschannel.InnerFecRate = (BinaryConvolutionCodeRate)detail.InnerFecRate;
         dvbschannel.Pilot = (Pilot)detail.Pilot;
         dvbschannel.Rolloff = (RollOff)detail.RollOff;
         dvbschannel.DisEqc = (DisEqcType)detail.Diseqc;
       }
     }
     return this.CurrentChannel.IsDifferentTransponder(dvbschannel);
   }
   else
     return false;  
 }
Esempio n. 13
0
 /// <summary>
 /// Sends the diseq command.
 /// </summary>
 /// <param name="channel">The channel.</param>
 /// <param name="parameters">The scanparameters.</param>
 public void SendDiseqCommand(ScanParameters parameters, DVBSChannel channel)
 {
   if (_previousChannel != null)
   {
     if (_previousChannel.Frequency == channel.Frequency &&
         _previousChannel.DisEqc == channel.DisEqc &&
         _previousChannel.Polarisation == channel.Polarisation)
     {
       Log.Log.WriteFile("TechnoTrend: already tuned to diseqc:{0}, frequency:{1}, polarisation:{2}", channel.DisEqc,
                         channel.Frequency, channel.Polarisation);
       return;
     }
   }
   _previousChannel = channel;
   int antennaNr = BandTypeConverter.GetAntennaNr(channel);
   //"01,02,03,04,05,06,07,08,09,0a,0b,cc,cc,cc,cc,cc,cc,cc,cc,cc,cc,cc,cc,cc,cc,"	
   Marshal.WriteByte(_ptrDataInstance, 0, 0xE0); //diseqc command 1. uFraming=0xe0
   Marshal.WriteByte(_ptrDataInstance, 1, 0x10); //diseqc command 1. uAddress=0x10
   Marshal.WriteByte(_ptrDataInstance, 2, 0x38); //diseqc command 1. uCommand=0x38
   //bit 0	(1)	: 0=low band, 1 = hi band
   //bit 1 (2) : 0=vertical, 1 = horizontal
   //bit 3 (4) : 0=satellite position A, 1=satellite position B
   //bit 4 (8) : 0=switch option A, 1=switch option  B
   // LNB    option  position
   // 1        A         A
   // 2        A         B
   // 3        B         A
   // 4        B         B
   bool hiBand = BandTypeConverter.IsHiBand(channel, parameters);
   Log.Log.WriteFile(
     "TechnoTrend SendDiseqcCommand() diseqc:{0}, antenna:{1} frequency:{2}, polarisation:{3} hiband:{4}",
     channel.DisEqc, antennaNr, channel.Frequency, channel.Polarisation, hiBand);
   bool isHorizontal = ((channel.Polarisation == Polarisation.LinearH) ||
                        (channel.Polarisation == Polarisation.CircularL));
   byte cmd = 0xf0;
   cmd |= (byte)(hiBand ? 1 : 0);
   cmd |= (byte)((isHorizontal) ? 2 : 0);
   cmd |= (byte)((antennaNr - 1) << 2);
   Marshal.WriteByte(_ptrDataInstance, 3, cmd);
   bdaapiSetDiSEqCMsg(m_hBdaApi, _ptrDataInstance, 4, 1, 0, (short)channel.Polarisation);
   Log.Log.Info("TechnoTrend: Diseqc Command Send");
 }
Esempio n. 14
0
 /// <summary>
 /// Set parameter to null when stopping the Graph.
 /// </summary>
 public void OnStopGraph()
 {
   _readCamName = true;
   _previousChannel = null;
   StopCiHandlerThread();
 }
Esempio n. 15
0
    /// <summary>
    /// Initializes a new instance of the <see cref="DigitalEverywhere"/> class.
    /// </summary>
    /// <param name="tunerFilter">The tuner filter.</param>
    public DigitalEverywhere(IBaseFilter tunerFilter)
    {
      _previousChannel = null;
      _filterTuner = tunerFilter;
      _hasCAM = false;
      _isInitialized = false;
      _isDigitalEverywhere = false;

      _ptrDataInstance = Marshal.AllocCoTaskMem(CA_DATA_SIZE);
      _ptrDataReturned = Marshal.AllocCoTaskMem(CA_DATA_SIZE);
      _ptrDataCiHandler = Marshal.AllocCoTaskMem(CA_DATA_SIZE);
      if (_filterTuner != null)
      {
        _isDigitalEverywhere = IsDigitalEverywhere;
        if (_isDigitalEverywhere)
        {
          _hasCAM = IsCamPresent();
          Log.Log.WriteFile("FireDTV cam detected  : {0}", _hasCAM);
          if (_hasCAM)
          {
            Log.Log.WriteFile("FireDTV cam name      : \"{0}\"", GetCAMName());
          }
          Log.Log.WriteFile("FireDTV driver version: {0}", GetDriverVersionNumber());
          Log.Log.WriteFile("FireDTV board version : {0}", GetHardwareFirmwareVersionNumber());
        }
      }
      _readCamName = true;
      _isInitialized = true;
    }
Esempio n. 16
0
    /// <summary>
    /// Gets the Antenna Number (or LNB number)
    /// </summary>
    /// <param name="channel">holds tuning details for DVB-S</param>
    /// <returns></returns>
    public static int GetAntennaNr(DVBSChannel channel)
    {
      byte disEqcPort = 0;

      switch (channel.DisEqc)
      {
        case DisEqcType.None:
          disEqcPort = 0; //no diseqc
          break;
        case DisEqcType.SimpleA: //simple A
          disEqcPort = 1;
          break;
        case DisEqcType.SimpleB: //simple B
          disEqcPort = 2;
          break;
        case DisEqcType.Level1AA: //Level 1 A/A
          disEqcPort = 1;
          break;
        case DisEqcType.Level1AB: //Level 1 A/B
          disEqcPort = 2;
          break;
        case DisEqcType.Level1BA: //Level 1 B/A
          disEqcPort = 3;
          break;
        case DisEqcType.Level1BB: //Level 1 B/B
          disEqcPort = 4;
          break;
      }
      return disEqcPort;
    }
Esempio n. 17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DVBSChannel"/> class.
 /// </summary>
 /// <param name="chan">The chan.</param>
 public DVBSChannel(DVBSChannel chan)
   : base(chan)
 {
   _polarisation = chan.Polarisation;
   _symbolRate = chan.SymbolRate;
   _switchingFrequency = chan.SwitchingFrequency;
   DisEqc = chan.DisEqc;
   _bandType = chan.BandType;
   _modulation = chan.ModulationType;
   _innerFecRate = chan.InnerFecRate;
   _pilot = chan.Pilot;
   _rollOff = chan.Rolloff;
   _satelliteIndex = chan.SatelliteIndex;
 }
Esempio n. 18
0
    /// <summary>
    /// Determins if the tuning paramter is HiBand and if so involke the 22Khz switch.
    /// </summary>
    /// <param name="channel">tuning details for specific channel / frequency</param>
    /// <param name="parameters">holds the parameters needed for tuning channel </param>
    /// <returns></returns>
    public static bool IsHiBand(DVBSChannel channel, ScanParameters parameters)
    {
      int lof1, lof2, sw;
      GetDefaultLnbSetup(parameters, channel.BandType, out lof1, out lof2, out sw);

      if (sw == 0)
      {
        return false;
      }
      return channel.Frequency >= (sw * 1000);
    }
Esempio n. 19
0
 /// <summary>
 /// Sends the diseq command.
 /// </summary>
 /// <param name="channel">The channel.</param>
 /// <param name="parameters">The scanparameters.</param>
 public void SendDiseqCommand(ScanParameters parameters, DVBSChannel channel)
 {
   switch (channel.DisEqc)
   {
     case DisEqcType.Level1AA:
       Log.Log.Info("KNC:  Level1AA - SendDiSEqCCommand(0x00)");
       SendDiSEqCCommand(0x00);
       break;
     case DisEqcType.Level1AB:
       Log.Log.Info("KNC:  Level1AB - SendDiSEqCCommand(0x01)");
       SendDiSEqCCommand(0x01);
       break;
     case DisEqcType.Level1BA:
       Log.Log.Info("KNC:  Level1BA - SendDiSEqCCommand(0x0100)");
       SendDiSEqCCommand(0x0100);
       break;
     case DisEqcType.Level1BB:
       Log.Log.Info("KNC:  Level1BB - SendDiSEqCCommand(0x0101)");
       SendDiSEqCCommand(0x0101);
       break;
     case DisEqcType.SimpleA:
       Log.Log.Info("KNC:  SimpleA - SendDiSEqCCommand(0x00)");
       SendDiSEqCCommand(0x00);
       break;
     case DisEqcType.SimpleB:
       Log.Log.Info("KNC:  SimpleB - SendDiSEqCCommand(0x01)");
       SendDiSEqCCommand(0x01);
       break;
     default:
       return;
   }
 }
Esempio n. 20
0
    /// <summary>
    /// Sends the diseq command.
    /// </summary>
    /// <param name="channel">The channel.</param>
    /// <param name="parameters">The scanparameters.</param>
    public void SendDiseqCommand(ScanParameters parameters, DVBSChannel channel)
    {
      if (m_bIsTeVii == false)
        return;
      Log.Log.Debug("TeVii: SendDiseqc: {0},{1}", parameters.ToString(), channel.ToString());

      //bit 0	(1)	: 0=low band, 1 = hi band
      //bit 1 (2) : 0=vertical, 1 = horizontal
      //bit 3 (4) : 0=satellite position A, 1=satellite position B
      //bit 4 (8) : 0=switch option A, 1=switch option  B
      // LNB    option  position
      // 1        A         A
      // 2        A         B
      // 3        B         A
      // 4        B         B
      int antennaNr = BandTypeConverter.GetAntennaNr(channel);
      bool hiBand = BandTypeConverter.IsHiBand(channel, parameters);
      bool isHorizontal = ((channel.Polarisation == Polarisation.LinearH) ||
                           (channel.Polarisation == Polarisation.CircularL));
      byte cmd = 0xf0;
      cmd |= (byte)(hiBand ? 1 : 0);
      cmd |= (byte)((isHorizontal) ? 2 : 0);
      cmd |= (byte)((antennaNr - 1) << 2);

      byte[] ucMessage = new byte[4];
      ucMessage[0] = 0xE0; //framing byte
      ucMessage[1] = 0x10; //address byte
      ucMessage[2] = 0x38; //command byte
      ucMessage[3] = cmd; //data byte (port group 0)
      //byte[] ucMessage = DiSEqC_Helper.ChannelToDiSEqC(parameters, channel);
      SendDiSEqCCommand(ucMessage);
    }
Esempio n. 21
0
    /// <summary>
    /// Sends the diseq command.
    /// </summary>
    /// <param name="channel">The channel.</param>
    /// <param name="parameters">The scanparameters.</param>
    public bool SendDiseqCommand(ScanParameters parameters, DVBSChannel channel)
    {
      bool succeeded = true;
      if (_isHauppauge == false)
        return true;
      int antennaNr = BandTypeConverter.GetAntennaNr(channel);
      if (antennaNr == 0)
        return true;
      //clear the message params before writing in order to avoid corruption of the diseqc message.
      for (int i = 0; i < 188; ++i)
      {
        Marshal.WriteByte(_ptrDiseqc, i, 0x00);
      }
      bool hiBand = BandTypeConverter.IsHiBand(channel, parameters);
      //bit 0	(1)	: 0=low band, 1 = hi band
      //bit 1 (2) : 0=vertical, 1 = horizontal
      //bit 3 (4) : 0=satellite position A, 1=satellite position B
      //bit 4 (8) : 0=switch option A, 1=switch option  B
      // LNB    option  position
      // 1        A         A
      // 2        A         B
      // 3        B         A
      // 4        B         B
      bool isHorizontal = ((channel.Polarisation == Polarisation.LinearH) ||
                           (channel.Polarisation == Polarisation.CircularL));
      byte cmd = 0xf0;
      cmd |= (byte)(hiBand ? 1 : 0);
      cmd |= (byte)((isHorizontal) ? 2 : 0);
      cmd |= (byte)((antennaNr - 1) << 2);

      const int len = 188; //hauppauge diseqc message length
      ulong diseqc = 0xE0103800; //currently committed switches only. i.e. ports 1-4
      diseqc += cmd;

      Marshal.WriteByte(_ptrDiseqc, 0, (byte)((diseqc >> 24) & 0xff)); //framing byte
      Marshal.WriteByte(_ptrDiseqc, 1, (byte)((diseqc >> 16) & 0xff)); //address byte
      Marshal.WriteByte(_ptrDiseqc, 2, (byte)((diseqc >> 8) & 0xff)); //command byte
      Marshal.WriteByte(_ptrDiseqc, 3, (byte)(diseqc & 0xff)); //data byte (port group 0)
      Marshal.WriteInt32(_ptrDiseqc, 160, 4); //send_message_length
      Marshal.WriteInt32(_ptrDiseqc, 164, 0); //receive_message_length
      Marshal.WriteInt32(_ptrDiseqc, 168, 3); //amplitude_attenuation
      if (antennaNr == 1) //for simple diseqc switches (i.e. 22KHz tone burst)
      {
        Marshal.WriteByte(_ptrDiseqc, 172, (int)BurstModulationType.TONE_BURST_UNMODULATED);
      }
      else
      {
        Marshal.WriteByte(_ptrDiseqc, 172, (int)BurstModulationType.TONE_BURST_MODULATED);
        //default to tone_burst_modulated
      }
      Marshal.WriteByte(_ptrDiseqc, 176, (int)DisEqcVersion.DISEQC_VER_1X); //default
      Marshal.WriteByte(_ptrDiseqc, 180, (int)RxMode.RXMODE_NOREPLY); //default
      Marshal.WriteByte(_ptrDiseqc, 184, 1); //last_message TRUE */

      string txt = "";
      for (int i = 0; i < 4; ++i)
        txt += String.Format("0x{0:X} ", Marshal.ReadByte(_ptrDiseqc, i));
      for (int i = 160; i < 188; i = (i + 4))
        txt += String.Format("0x{0:X} ", Marshal.ReadInt32(_ptrDiseqc, i));
      Log.Log.Debug("Hauppauge: SendDiseq: {0}", txt);
      int hr = _propertySet.Set(BdaTunerExtentionProperties, (int)BdaTunerExtension.KSPROPERTY_BDA_DISEQC, _ptrDiseqc,
                                len, _ptrDiseqc, len);
      if (hr != 0)
      {
        succeeded = false;
        Log.Log.Info("Hauppauge: SendDiseq returned: 0x{0:X} - {1}", hr, DsError.GetErrorText(hr));
      }
      return succeeded;
    }
Esempio n. 22
0
 /// <summary>
 /// sets the dvb-s2 pilot / roll-off
 /// </summary>
 public void SetDVBS2PilotRolloff(DVBSChannel channel)
 {
   //Set the Pilot
   int hr;
   KSPropertySupport supported;
   _propertySet.QuerySupported(BdaTunerExtentionProperties, (int)BdaTunerExtension.KSPROPERTY_BDA_PILOT,
                               out supported);
   if ((supported & KSPropertySupport.Set) == KSPropertySupport.Set)
   {
     Log.Log.Debug("Hauppauge: Set Pilot: {0}", channel.Pilot);
     Marshal.WriteInt32(_tempValue, (Int32)channel.Pilot);
     hr = _propertySet.Set(BdaTunerExtentionProperties, (int)BdaTunerExtension.KSPROPERTY_BDA_PILOT, _tempInstance,
                           32, _tempValue, 4);
     if (hr != 0)
     {
       Log.Log.Info("Hauppauge: Set Pilot returned: 0x{0:X} - {1}", hr, DsError.GetErrorText(hr));
     }
   }
   //Set the Roll-off
   _propertySet.QuerySupported(BdaTunerExtentionProperties, (int)BdaTunerExtension.KSPROPERTY_BDA_ROLL_OFF,
                               out supported);
   if ((supported & KSPropertySupport.Set) == KSPropertySupport.Set)
   {
     Log.Log.Debug("Hauppauge: Set Roll-Off: {0}", channel.Rolloff);
     Marshal.WriteInt32(_tempValue, (Int32)channel.Rolloff);
     hr = _propertySet.Set(BdaTunerExtentionProperties, (int)BdaTunerExtension.KSPROPERTY_BDA_ROLL_OFF, _tempInstance,
                           32, _tempValue, 4);
     if (hr != 0)
     {
       Log.Log.Info("Hauppauge: Set Roll-Off returned: 0x{0:X} - {1}", hr, DsError.GetErrorText(hr));
     }
   }
 }
Esempio n. 23
0
    ///<summary>
    /// Scan NIT channel
    ///</summary>
    ///<param name="channel">Channel</param>
    ///<param name="settings">Scan Parameters</param>
    ///<returns>Found channels</returns>
    public List<IChannel> ScanNIT(IChannel channel, ScanParameters settings)
    {
      try
      {
        _card.IsScanning = true;
        _card.Scan(0, channel);
        _analyzer = GetAnalyzer();
        if (_analyzer == null)
        {
          Log.Log.WriteFile("Scan: no analyzer interface available");
          return new List<IChannel>();
        }
        _analyzer.SetCallBack(null);
        _analyzer.ScanNIT();
        Thread.Sleep(settings.TimeOutTune * 1000);
        ResetSignalUpdate();
        Log.Log.WriteFile("ScanNIT: tuner locked:{0} signal:{1} quality:{2}", _card.IsTunerLocked, _card.SignalLevel,
                          _card.SignalQuality);
        if (_card.IsTunerLocked || _card.SignalLevel > 0 || _card.SignalQuality > 0)
        {
          int count;

          _event = new ManualResetEvent(false);
          _event.WaitOne(16000, true);
          _event.Close();
          List<IChannel> channelsFound = new List<IChannel>();
          _analyzer.GetNITCount(out count);
          for (int i = 0; i < count; ++i)
          {
            int freq, pol, mod, symbolrate, bandwidth, innerfec, rollOff, chType;
            IntPtr ptrName;
            _analyzer.GetNITChannel((short)i, out chType, out freq, out pol, out mod, out symbolrate, out bandwidth,
                                    out innerfec, out rollOff, out ptrName);
            string name = DvbTextConverter.Convert(ptrName, "");
            if (chType == 0)
            {
              DVBSChannel ch = new DVBSChannel();
              ch.Name = name;
              ch.Frequency = freq;
              Log.Log.Debug("{0},{1},{2},{3}", freq, mod, pol, symbolrate);
              switch (mod)
              {
                default:
                case 0:
                  ch.ModulationType = ModulationType.ModNotSet;
                  break;
                  //case 1: ch.ModulationType = ModulationType.ModQpsk; break;
                case 2:
                  ch.ModulationType = ModulationType.Mod8Psk;
                  break;
                case 3:
                  ch.ModulationType = ModulationType.Mod16Qam;
                  break;
              }
              ch.SymbolRate = symbolrate;
              ch.InnerFecRate = (BinaryConvolutionCodeRate)innerfec;
              ch.Polarisation = (Polarisation)pol;
              ch.Rolloff = (RollOff)rollOff;
              channelsFound.Add(ch);
            }
            else if (chType == 1)
            {
              DVBCChannel ch = new DVBCChannel();
              ch.Name = name;
              ch.Frequency = freq;
              ch.ModulationType = (ModulationType)mod;
              ch.SymbolRate = symbolrate;
              channelsFound.Add(ch);
            }
            else if (chType == 2)
            {
              DVBTChannel ch = new DVBTChannel();
              ch.Name = name;
              ch.Frequency = freq;
              ch.BandWidth = bandwidth;
              channelsFound.Add(ch);
            }
          }
          _analyzer.StopNIT();
          return channelsFound;
        }
        else
        {
          Log.Log.WriteFile("Scan: no signal detected");
          return new List<IChannel>();
        }
      }
      finally
      {
        if (_analyzer != null)
        {
          _analyzer.StopNIT();
        }
        _card.IsScanning = false;
      }
    }
Esempio n. 24
0
    private bool BeforeTune(ref int subChannelId, IChannel channel)
    {
      DVBSChannel dvbsChannel = channel as DVBSChannel;
      if (dvbsChannel == null)
      {
        Log.Log.WriteFile("Channel is not a DVBS channel!!! {0}", channel.GetType().ToString());
        return false;
      }
      /*if (CurrentChannel != null)
      {
        //@FIX this fails for back-2-back recordings
        //if (oldChannel.Equals(channel)) return _mapSubChannels[0];
      }*/
      if (dvbsChannel.SwitchingFrequency < 10)
      {
        dvbsChannel.SwitchingFrequency = 11700000;
      }
      Log.Log.WriteFile("dvbs:  Tune:{0}", channel);
      if (_graphState == GraphState.Idle)
      {
        BuildGraph();
      }
      if (_mapSubChannels.ContainsKey(subChannelId) == false)
      {
        subChannelId = GetNewSubChannel(channel);
      }
      if (useInternalNetworkProvider)
      {
        //set the DisEqC parameters 
        if (_conditionalAccess != null)
        {
          //int hr2 = ((IMediaControl)_graphBuilder).Pause();
          _diseqCsucceded = _conditionalAccess.SendDiseqcCommand(_parameters, dvbsChannel);
          //hr2 = ((IMediaControl)_graphBuilder).Run();

          //move diseqc motor to correct satellite
          if (dvbsChannel != null && dvbsChannel.SatelliteIndex > 0 && _conditionalAccess.DiSEqCMotor != null)
          {
            _conditionalAccess.DiSEqCMotor.GotoPosition((byte)dvbsChannel.SatelliteIndex);
          }
        }
        return true;
      }

      if (_previousChannel == null || _previousChannel.IsDifferentTransponder(dvbsChannel))
      {
        //_pmtPid = -1;
        ILocator locator;
        int lowOsc;
        int hiOsc;
        int lnbSwitch;
        BandTypeConverter.GetDefaultLnbSetup(Parameters, dvbsChannel.BandType, out lowOsc, out hiOsc, out lnbSwitch);
        Log.Log.Info("LNB low:{0} hi:{1} switch:{2}", lowOsc, hiOsc, lnbSwitch);
        if (lnbSwitch == 0)
          lnbSwitch = 18000;
        IDVBSTuningSpace tuningSpace = (IDVBSTuningSpace)_tuningSpace;
        tuningSpace.put_LNBSwitch(lnbSwitch * 1000);
        tuningSpace.put_LowOscillator(lowOsc * 1000);
        tuningSpace.put_HighOscillator(hiOsc * 1000);
        ITuneRequest request;
        _tuningSpace.CreateTuneRequest(out request);
        _tuneRequest = (IDVBTuneRequest)request;
        _tuningSpace.get_DefaultLocator(out locator);
        IDVBSLocator dvbsLocator = (IDVBSLocator)locator;
        IDVBTuneRequest tuneRequest = (IDVBTuneRequest)_tuneRequest;
        tuneRequest.put_ONID(dvbsChannel.NetworkId);
        tuneRequest.put_SID(dvbsChannel.ServiceId);
        tuneRequest.put_TSID(dvbsChannel.TransportId);
        locator.put_CarrierFrequency((int)dvbsChannel.Frequency);
        dvbsLocator.put_SymbolRate(dvbsChannel.SymbolRate);
        dvbsLocator.put_SignalPolarisation(dvbsChannel.Polarisation);

        // Set DVB-S2 and manufacturer specific tuning parameters here.
        //-------------------------------------------------------------------
        // Important: the original dvbsChannel object *must not* be modified
        // otherwise IsDifferentTransponder() will sometimes returns true
        // when it shouldn't. See mantis 0002979.
        //-------------------------------------------------------------------
        DVBSChannel tuneChannel = new DVBSChannel(dvbsChannel);
        if (_conditionalAccess != null)
        {
          tuneChannel = _conditionalAccess.SetDVBS2Modulation(_parameters, tuneChannel);
        }
        dvbsLocator.put_Modulation(tuneChannel.ModulationType);
        Log.Log.WriteFile("dvbs:channel modulation is set to {0}", tuneChannel.ModulationType);
        dvbsLocator.put_InnerFECRate(tuneChannel.InnerFecRate);
        Log.Log.WriteFile("dvbs:channel FECRate is set to {0}", tuneChannel.InnerFecRate);
        _tuneRequest.put_Locator(locator);

        //set the DisEqC parameters 
        if (_conditionalAccess != null)
        {
          //int hr2 = ((IMediaControl)_graphBuilder).Pause();
          _diseqCsucceded = _conditionalAccess.SendDiseqcCommand(_parameters, dvbsChannel);
          //hr2 = ((IMediaControl)_graphBuilder).Run();

          //move diseqc motor to correct satellite
          if (dvbsChannel != null && dvbsChannel.SatelliteIndex > 0 && _conditionalAccess.DiSEqCMotor != null)
          {
            _conditionalAccess.DiSEqCMotor.GotoPosition((byte)dvbsChannel.SatelliteIndex);
          }
        }
      }

      _dvbsChannel = dvbsChannel;
      return true;
    }
Esempio n. 25
0
    /// <summary>
    /// Sends the diseq command.
    /// </summary>
    /// <param name="channel">The channel.</param>
    /// <param name="parameters">The channels scanning parameters.</param>
    public void SendDiseqCommand(ScanParameters parameters, DVBSChannel channel)
    {
      if (_isProfRed == false)
        return;
      if (_previousChannel != null)
      {
        if (_previousChannel.Frequency == channel.Frequency &&
            _previousChannel.DisEqc == channel.DisEqc &&
            _previousChannel.Polarisation == channel.Polarisation &&
            _previousChannel.Pilot == channel.Pilot &&
            _previousChannel.Rolloff == channel.Rolloff &&
            _previousChannel.InnerFecRate == channel.InnerFecRate)
        {
          _previousChannel = channel;
          Log.Log.WriteFile("ProfRed: already tuned to diseqc:{0}, frequency:{1}, polarisation:{2}",
                            channel.DisEqc, channel.Frequency, channel.Polarisation);
          return;
        }
        if (_previousChannel.DisEqc == DisEqcType.None && channel.DisEqc == DisEqcType.None)
        {
          _previousChannel = channel;
          Log.Log.WriteFile("ProfRed: already no diseqc used",
                            channel.DisEqc, channel.Frequency, channel.Polarisation);
          return;
        }
      }
      if (_previousChannel == null && channel.DisEqc == DisEqcType.None)
      {
        _previousChannel = channel;
        Log.Log.WriteFile("ProfRed: diseqc isn't used - skip it",
                          channel.DisEqc, channel.Frequency, channel.Polarisation);
        return;
      }
      _previousChannel = channel;
      int antennaNr = BandTypeConverter.GetAntennaNr(channel);
      //hack - bypass diseqc settings for single LNB implementations
      if (antennaNr == 0)
        return;
      //end of hack

      //clear the message params before writing in order to avoid corruption of the diseqc message.
      for (int i = 0; i < 188; ++i)
      {
        Marshal.WriteByte(_ptrDiseqc, i, 0x00);
      }

      bool hiBand = BandTypeConverter.IsHiBand(channel, parameters);


      //bit 0	(1)	: 0=low band, 1 = hi band
      //bit 1 (2) : 0=vertical, 1 = horizontal
      //bit 3 (4) : 0=satellite position A, 1=satellite position B
      //bit 4 (8) : 0=switch option A, 1=switch option  B
      // LNB    option  position
      // 1        A         A
      // 2        A         B
      // 3        B         A
      // 4        B         B

      bool isHorizontal = ((channel.Polarisation == Polarisation.LinearH) ||
                           (channel.Polarisation == Polarisation.CircularL));
      byte cmd = 0xf0;
      cmd |= (byte)(hiBand ? 1 : 0);
      cmd |= (byte)((isHorizontal) ? 2 : 0);
      cmd |= (byte)((antennaNr - 1) << 2);

      const int len = 188;
      ulong diseqc = 0xE0103800; //currently committed switches only. i.e. ports 1-4
      diseqc += cmd;
      Marshal.WriteByte(_ptrDiseqc, 0, (byte)((diseqc >> 24) & 0xff)); //framing byte
      Marshal.WriteByte(_ptrDiseqc, 1, (byte)((diseqc >> 16) & 0xff)); //address byte
      Marshal.WriteByte(_ptrDiseqc, 2, (byte)((diseqc >> 8) & 0xff)); //command byte
      Marshal.WriteByte(_ptrDiseqc, 3, (byte)(diseqc & 0xff)); //data byte (port group 0)
      Marshal.WriteByte(_ptrDiseqc, 151, 4); //send_message_length
      Marshal.WriteByte(_ptrDiseqc, 161, 0); //receive_message_length

      if (antennaNr == 1) //for simple diseqc switches (i.e. 22KHz tone burst)
      {
        Marshal.WriteByte(_ptrDiseqc, 164, 2); // TONE_BURST_UNMODULATED
      }
      else
      {
        Marshal.WriteByte(_ptrDiseqc, 164, 1); // TONE_BURST_MODULATED
      }
      Marshal.WriteByte(_ptrDiseqc, 172, 3); //default for Diseqc
      Marshal.WriteByte(_ptrDiseqc, 168, 2); //RxMode.RXMODE_NOREPLY);//default
      Marshal.WriteByte(_ptrDiseqc, 180, 1); //last_message TRUE */
      string txt = "";
      for (int i = 0; i < 4; ++i)
        txt += String.Format("0x{0:X} ", Marshal.ReadByte(_ptrDiseqc, i));
      txt += String.Format("0x{0:X} ", Marshal.ReadByte(_ptrDiseqc, 151)); //send_message_length
      for (int i = 164; i < 188; i += 4)
        txt += String.Format("0x{0:X} ", Marshal.ReadInt32(_ptrDiseqc, i));
      Log.Log.WriteFile("ProfRed: SendDiseq: {0}", txt);

      int retval; //out value
      int hr = _propertySet.Get(_bdaTunerExtentionProperties, (int)BdaTunerExtension.KSPROPERTY_BDA_DISEQC, _ptrDiseqc,
                                len, _ptrDiseqc, len, out retval);
      Log.Log.Info("ProfRed: setdiseqc returned:{0:X}", hr);
    }
Esempio n. 26
0
 protected override DVBBaseChannel CreateChannel(int networkid, int transportid, int serviceid, string name)
 {
   DVBSChannel channel = new DVBSChannel();
   channel.NetworkId = networkid;
   channel.TransportId = transportid;
   channel.ServiceId = serviceid;
   channel.Name = name;
   return channel;
 }
Esempio n. 27
0
 /// <summary>
 /// sends the diseqc command to the card
 /// </summary>
 /// <param name="parameters">The parameters.</param>
 /// <param name="channel">The current tv/radio channel</param>
 public bool SendDiseqcCommand(ScanParameters parameters, DVBSChannel channel)
 {
   bool succeeded = true;
   try
   {
     if (_knc != null)
     {
       _knc.SendDiseqCommand(parameters, channel);
       System.Threading.Thread.Sleep(100);
     }
     if (_digitalEveryWhere != null)
     {
       _digitalEveryWhere.SendDiseqcCommand(parameters, channel);
       System.Threading.Thread.Sleep(100);
     }
     if (_technoTrend != null)
     {
       _technoTrend.SendDiseqCommand(parameters, channel);
       System.Threading.Thread.Sleep(100);
     }
     if (_twinhan != null)
     {
       _twinhan.SendDiseqCommand(parameters, channel);
       System.Threading.Thread.Sleep(100);
     }
     if (_hauppauge != null)
     {
       succeeded = _hauppauge.SendDiseqCommand(parameters, channel);
       System.Threading.Thread.Sleep(100);
     }
     if (_genericbdas != null)
     {
       _genericbdas.SendDiseqCommand(parameters, channel);
       System.Threading.Thread.Sleep(100);
     }
     if (_conexant != null)
     {
       _conexant.SendDiseqCommand(parameters, channel);
       System.Threading.Thread.Sleep(100);
     }
     if (_profred != null)
     {
       _profred.SendDiseqCommand(parameters, channel);
       System.Threading.Thread.Sleep(100);
     }
     if (_genpix != null)
     {
       _genpix.SendDiseqCommand(parameters, channel);
       System.Threading.Thread.Sleep(100);
     }
     if (_TeVii != null)
     {
       _TeVii.SendDiseqCommand(parameters, channel);
       System.Threading.Thread.Sleep(100);
     }
   }
   catch (Exception ex)
   {
     Log.Log.Write(ex);
   }
   return succeeded;
 }
Esempio n. 28
0
 ///<summary>
 /// Send DiseqC Command test
 ///</summary>
 ///<param name="parameters">Scan parameters</param>
 ///<param name="channel">Channel</param>
 public void SendDiseqcCommandTest(ScanParameters parameters, DVBSChannel channel)
 {
   int antennaNr = BandTypeConverter.GetAntennaNr(channel);
   bool hiBand = BandTypeConverter.IsHiBand(channel, parameters);
   bool isHorizontal = ((channel.Polarisation == Polarisation.LinearH) ||
                        (channel.Polarisation == Polarisation.CircularL));
   byte cmd = 0xf0;
   cmd |= (byte)(hiBand ? 1 : 0);
   cmd |= (byte)((isHorizontal) ? 2 : 0);
   cmd |= (byte)((antennaNr - 1) << 2);
   byte[] diseqc = new byte[4];
   diseqc[0] = 0xe0;
   diseqc[1] = 0x10;
   diseqc[2] = 0x38;
   diseqc[3] = cmd;
   SendDiSEqCCommand(diseqc);
 }
Esempio n. 29
0
    /// <summary>
    /// Sends the diseqc command.
    /// </summary>
    /// <param name="channel">The channel.</param>
    /// <param name="parameters">The scanparameters.</param>
    public void SendDiseqcCommand(ScanParameters parameters, DVBSChannel channel)
    {
      if (_previousChannel != null)
      {
        if (_previousChannel.Frequency == channel.Frequency &&
            _previousChannel.DisEqc == channel.DisEqc &&
            _previousChannel.Polarisation == channel.Polarisation &&
            _previousChannel.Pilot == channel.Pilot &&
            _previousChannel.Rolloff == channel.Rolloff &&
            _previousChannel.InnerFecRate == channel.InnerFecRate)
        {
          _previousChannel = channel;
          Log.Log.WriteFile("FireDTV: already tuned to diseqc:{0}, frequency:{1}, polarisation:{2}",
                            channel.DisEqc, channel.Frequency, channel.Polarisation);
          return;
        }
        if (_previousChannel.DisEqc == DisEqcType.None && channel.DisEqc == DisEqcType.None)
        {
          _previousChannel = channel;
          Log.Log.WriteFile("FireDTV: already no diseqc used",
                            channel.DisEqc, channel.Frequency, channel.Polarisation);
          return;
        }
      }
      if (_previousChannel == null && channel.DisEqc == DisEqcType.None)
      {
        _previousChannel = channel;
        Log.Log.WriteFile("FireDTV: diseqc isn't used - skip it",
                          channel.DisEqc, channel.Frequency, channel.Polarisation);
        return;
      }
      _previousChannel = channel;
      int antennaNr = BandTypeConverter.GetAntennaNr(channel);

      //"01,02,03,04,05,06,07,08,09,0a,0b,cc,cc,cc,cc,cc,cc,cc,cc,cc,cc,cc,cc,cc,cc,"	

      Marshal.WriteByte(_ptrDataInstance, 0, 0xFF); //Voltage;
      Marshal.WriteByte(_ptrDataInstance, 1, 0xFF); //ContTone;
      Marshal.WriteByte(_ptrDataInstance, 2, 0xFF); //Burst;
      Marshal.WriteByte(_ptrDataInstance, 3, 0x01); //NrDiseqcCmds;

      Marshal.WriteByte(_ptrDataInstance, 4, 0x04); //diseqc command 1. length=4
      Marshal.WriteByte(_ptrDataInstance, 5, 0xE0); //diseqc command 1. uFraming=0xe0
      Marshal.WriteByte(_ptrDataInstance, 6, 0x10); //diseqc command 1. uAddress=0x10
      Marshal.WriteByte(_ptrDataInstance, 7, 0x38); //diseqc command 1. uCommand=0x38


      //bit 0	(1)	: 0=low band, 1 = hi band
      //bit 1 (2) : 0=vertical, 1 = horizontal
      //bit 3 (4) : 0=satellite position A, 1=satellite position B
      //bit 4 (8) : 0=switch option A, 1=switch option  B
      // LNB    option  position
      // 1        A         A
      // 2        A         B
      // 3        B         A
      // 4        B         B
      bool hiBand = BandTypeConverter.IsHiBand(channel, parameters);
      Log.Log.WriteFile(
        "FireDTV SendDiseqcCommand() diseqc:{0}, antenna:{1} frequency:{2},  polarisation:{3} hiband:{4}",
        channel.DisEqc, antennaNr, channel.Frequency, channel.Polarisation, hiBand);

      bool isHorizontal = ((channel.Polarisation == Polarisation.LinearH) ||
                           (channel.Polarisation == Polarisation.CircularL));
      byte cmd = 0xf0;
      cmd |= (byte)(hiBand ? 1 : 0);
      cmd |= (byte)((isHorizontal) ? 2 : 0);
      cmd |= (byte)((antennaNr - 1) << 2);
      Marshal.WriteByte(_ptrDataInstance, 8, cmd);

      Guid propertyGuid = KSPROPSETID_Firesat;
      const int propId = KSPROPERTY_FIRESAT_LNB_CONTROL;
      IKsPropertySet propertySet = _filterTuner as IKsPropertySet;
      KSPropertySupport isTypeSupported;
      if (propertySet == null)
      {
        Log.Log.WriteFile("FireDTV:SendDiseqcCommand() properySet=null");
        return;
      }

      int hr = propertySet.QuerySupported(propertyGuid, propId, out isTypeSupported);
      if (hr != 0 || (isTypeSupported & KSPropertySupport.Set) == 0)
      {
        Log.Log.WriteFile("FireDTV:SendDiseqcCommand() set is not supported {0:X} {1}", hr, (int)isTypeSupported);
        return;
      }

      string txt = "";
      for (int i = 0; i < 10; ++i)
        txt += String.Format("0x{0:X} ", Marshal.ReadByte(_ptrDataInstance, i));
      Log.Log.WriteFile("FireDTV:SendDiseq: {0}", txt);

      hr = propertySet.Set(propertyGuid, propId, _ptrDataInstance, 25, _ptrDataInstance, 25);
      if (hr != 0)
      {
        Log.Log.WriteFile("FireDTV:SendDiseqcCommand() failed:{0:X}", hr);
      }
    }
Esempio n. 30
0
 public IChannel GetTuningChannel(TuningDetail detail)
 {
   switch (detail.ChannelType)
   {
     case 0: //AnalogChannel
       AnalogChannel analogChannel = new AnalogChannel();
       analogChannel.ChannelNumber = detail.ChannelNumber;
       CountryCollection collection = new CountryCollection();
       analogChannel.Country = collection.Countries[detail.CountryId];
       analogChannel.Frequency = detail.Frequency;
       analogChannel.IsRadio = detail.IsRadio;
       analogChannel.IsTv = detail.IsTv;
       analogChannel.Name = detail.Name;
       analogChannel.TunerSource = (TunerInputType)detail.TuningSource;
       analogChannel.VideoSource = (AnalogChannel.VideoInputType)detail.VideoSource;
       analogChannel.AudioSource = (AnalogChannel.AudioInputType)detail.AudioSource;
       return analogChannel;
     case 1: //ATSCChannel
       ATSCChannel atscChannel = new ATSCChannel();
       atscChannel.MajorChannel = detail.MajorChannel;
       atscChannel.MinorChannel = detail.MinorChannel;
       atscChannel.PhysicalChannel = detail.ChannelNumber;
       atscChannel.FreeToAir = detail.FreeToAir;
       atscChannel.Frequency = detail.Frequency;
       atscChannel.IsRadio = detail.IsRadio;
       atscChannel.IsTv = detail.IsTv;
       atscChannel.Name = detail.Name;
       atscChannel.NetworkId = detail.NetworkId;
       atscChannel.PmtPid = detail.PmtPid;
       atscChannel.Provider = detail.Provider;
       atscChannel.ServiceId = detail.ServiceId;
       //atscChannel.SymbolRate = detail.Symbolrate;
       atscChannel.TransportId = detail.TransportId;
       atscChannel.ModulationType = (ModulationType)detail.Modulation;
       return atscChannel;
     case 2: //DVBCChannel
       DVBCChannel dvbcChannel = new DVBCChannel();
       dvbcChannel.ModulationType = (ModulationType)detail.Modulation;
       dvbcChannel.FreeToAir = detail.FreeToAir;
       dvbcChannel.Frequency = detail.Frequency;
       dvbcChannel.IsRadio = detail.IsRadio;
       dvbcChannel.IsTv = detail.IsTv;
       dvbcChannel.Name = detail.Name;
       dvbcChannel.NetworkId = detail.NetworkId;
       dvbcChannel.PmtPid = detail.PmtPid;
       dvbcChannel.Provider = detail.Provider;
       dvbcChannel.ServiceId = detail.ServiceId;
       dvbcChannel.SymbolRate = detail.Symbolrate;
       dvbcChannel.TransportId = detail.TransportId;
       dvbcChannel.LogicalChannelNumber = detail.ChannelNumber;
       return dvbcChannel;
     case 3: //DVBSChannel
       DVBSChannel dvbsChannel = new DVBSChannel();
       dvbsChannel.DisEqc = (DisEqcType)detail.Diseqc;
       dvbsChannel.Polarisation = (Polarisation)detail.Polarisation;
       dvbsChannel.SwitchingFrequency = detail.SwitchingFrequency;
       dvbsChannel.FreeToAir = detail.FreeToAir;
       dvbsChannel.Frequency = detail.Frequency;
       dvbsChannel.IsRadio = detail.IsRadio;
       dvbsChannel.IsTv = detail.IsTv;
       dvbsChannel.Name = detail.Name;
       dvbsChannel.NetworkId = detail.NetworkId;
       dvbsChannel.PmtPid = detail.PmtPid;
       dvbsChannel.Provider = detail.Provider;
       dvbsChannel.ServiceId = detail.ServiceId;
       dvbsChannel.SymbolRate = detail.Symbolrate;
       dvbsChannel.TransportId = detail.TransportId;
       dvbsChannel.BandType = (BandType)detail.Band;
       dvbsChannel.SatelliteIndex = detail.SatIndex;
       dvbsChannel.ModulationType = (ModulationType)detail.Modulation;
       dvbsChannel.InnerFecRate = (BinaryConvolutionCodeRate)detail.InnerFecRate;
       dvbsChannel.Pilot = (Pilot)detail.Pilot;
       dvbsChannel.Rolloff = (RollOff)detail.RollOff;
       dvbsChannel.LogicalChannelNumber = detail.ChannelNumber;
       return dvbsChannel;
     case 4: //DVBTChannel
       DVBTChannel dvbtChannel = new DVBTChannel();
       dvbtChannel.BandWidth = detail.Bandwidth;
       dvbtChannel.FreeToAir = detail.FreeToAir;
       dvbtChannel.Frequency = detail.Frequency;
       dvbtChannel.IsRadio = detail.IsRadio;
       dvbtChannel.IsTv = detail.IsTv;
       dvbtChannel.Name = detail.Name;
       dvbtChannel.NetworkId = detail.NetworkId;
       dvbtChannel.PmtPid = detail.PmtPid;
       dvbtChannel.Provider = detail.Provider;
       dvbtChannel.ServiceId = detail.ServiceId;
       dvbtChannel.TransportId = detail.TransportId;
       dvbtChannel.LogicalChannelNumber = detail.ChannelNumber;
       return dvbtChannel;
     case 7: //DVBIPChannel
       DVBIPChannel dvbipChannel = new DVBIPChannel();
       dvbipChannel.FreeToAir = detail.FreeToAir;
       dvbipChannel.IsRadio = detail.IsRadio;
       dvbipChannel.IsTv = detail.IsTv;
       dvbipChannel.Name = detail.Name;
       dvbipChannel.NetworkId = detail.NetworkId;
       dvbipChannel.PmtPid = detail.PmtPid;
       dvbipChannel.Provider = detail.Provider;
       dvbipChannel.ServiceId = detail.ServiceId;
       dvbipChannel.TransportId = detail.TransportId;
       dvbipChannel.LogicalChannelNumber = detail.ChannelNumber;
       dvbipChannel.Url = detail.Url;
       return dvbipChannel;
   }
   return null;
 }
Esempio n. 31
0
    /// <summary>
    /// Sends the diseq command.
    /// </summary>
    /// <param name="channel">The channel.</param>
    /// <param name="parameters">The channels scanning parameters.</param>
    public void SendDiseqCommand(ScanParameters parameters, DVBSChannel channel)
    {
      if (_isGenPix == false)
        return;
      Log.Log.Debug("SendDiseqc: {0},{1}", parameters.ToString(), channel.ToString());

      //bit 0	(1)	: 0=low band, 1 = hi band
      //bit 1 (2) : 0=vertical, 1 = horizontal
      //bit 3 (4) : 0=satellite position A, 1=satellite position B
      //bit 4 (8) : 0=switch option A, 1=switch option  B
      // LNB    option  position
      // 1        A         A
      // 2        A         B
      // 3        B         A
      // 4        B         B
      int antennaNr = BandTypeConverter.GetAntennaNr(channel);
      bool hiBand = BandTypeConverter.IsHiBand(channel, parameters);
      bool isHorizontal = ((channel.Polarisation == Polarisation.LinearH) ||
                           (channel.Polarisation == Polarisation.CircularL));
      byte cmd = 0xf0;
      cmd |= (byte)(hiBand ? 1 : 0);
      cmd |= (byte)((isHorizontal) ? 2 : 0);
      cmd |= (byte)((antennaNr - 1) << 2);

      DISEQC_COMMAND DiseqcCommand = new DISEQC_COMMAND();
      DiseqcCommand.ucMessage[0] = 0xE0; //framing byte
      DiseqcCommand.ucMessage[1] = 0x10; //address byte
      DiseqcCommand.ucMessage[2] = 0x38; //command byte
      DiseqcCommand.ucMessage[3] = cmd; //data byte (port group 0)
      DiseqcCommand.ucMessage[4] = 0; //Need not fill this up
      DiseqcCommand.ucMessage[5] = 0; //Need not fill this up
      DiseqcCommand.ucMessageLength = 4; //Number of Valid bytes in the Command.

      Marshal.StructureToPtr(DiseqcCommand, _ptrDiseqc, false);
      //get the length of the structure command - usually 7 bytes.
      int len = Marshal.SizeOf(DiseqcCommand);

      string txt = "";
      for (int i = 0; i < len; ++i)
        txt += String.Format("0x{0:X} ", Marshal.ReadByte(_ptrDiseqc, i));
      Log.Log.Debug("GenPix: SendDiseqCommand: {0} with length {1}", txt, len);
      //set the DisEqC command to the tuner pin
      int hr = _propertySet.Set(BdaTunerExtentionProperties, (int)BdaTunerExtension.KSPROPERTY_BDA_DISEQC,
                                _ptrTempInstance, 32, _ptrDiseqc, len);
      if (hr != 0)
      {
        Log.Log.Info("GenPix: SendDiseqCommand returned: 0x{0:X} - {1}{2}", hr, HResult.GetDXErrorString(hr),
                     DsError.GetErrorText(hr));
      }
    }