public void RequestNativeExpressAdView(Rect rect)
    {
        if (nativeState == AdsState.Loaded || nativeState == AdsState.Loading)
        {
            return;
        }
        // These ad units are configured to always serve test ads.
#if UNITY_EDITOR
        string adUnitId = "unused";
#elif UNITY_ANDROID
        string adUnitId = nativeAndroid;
#elif UNITY_IPHONE
        string adUnitId = nativeIOS;
#else
        string adUnitId = "unexpected_platform";
#endif
#if UNITY_ANDROID || UNITY_IOS || !EDITOR
        // Create a 320x150 native express ad at the top of the screen.
        this.nativeExpressAdView = new NativeExpressAdView(
            adUnitId,
            new AdSize(320, 150),
            AdPosition.Top);
        // Register for ad events.
        this.nativeExpressAdView.OnAdLoaded             += this.HandleNativeExpressAdLoaded;
        this.nativeExpressAdView.OnAdFailedToLoad       += this.HandleNativeExpresseAdFailedToLoad;
        this.nativeExpressAdView.OnAdOpening            += this.HandleNativeExpressAdOpened;
        this.nativeExpressAdView.OnAdClosed             += this.HandleNativeExpressAdClosed;
        this.nativeExpressAdView.OnAdLeavingApplication += this.HandleNativeExpressAdLeftApplication;

        // Load a native express ad.
        this.nativeExpressAdView.LoadAd(adRequest);
        nativeState = AdsState.Loading;
#endif
    }
 public void HandleInterstitialLoaded(object sender, EventArgs args)
 {
     print("Interstitial: Đã load xong");
     interstitialState = AdsState.Loaded;
     if (interstitialAutoShow)
     {
         ShowInterstitial();
     }
 }
 public void HandleRewardBasedVideoLoaded(object sender, EventArgs args)
 {
     print("Reward Based Video: Đã load xong");
     rewardState = AdsState.Loaded;
     this.callBack(false);
     if (rewardVideoAutoShow)
     {
         ShowRewardBasedVideo();
     }
 }
Example #4
0
        /// <summary>
        /// Read the ads state
        /// </summary>
        /// <returns></returns>
        public new AdsState ReadState()
        {
            AdsState result = new AdsState();

            stateInfo = client.ReadState();

            result.State       = (ushort)((short)stateInfo.AdsState);
            result.DeviceState = (ushort)((short)stateInfo.DeviceState);

            return(result);
        }
    public void ShowRewardBasedVideo()
    {
#if UNITY_ANDROID || UNITY_IOS || !EDITOR
        if (this.rewardBasedVideo.IsLoaded())
        {
            this.rewardBasedVideo.Show();
            rewardState         = AdsState.None;
            rewardVideoAutoShow = false;
        }
        else
        {
            //MonoBehaviour.print("Reward based video ad is not ready yet");
        }
#endif
    }
    public void ShowInterstitial()
    {
#if UNITY_ANDROID || UNITY_IOS || !EDITOR
        if (this.interstitial.IsLoaded())
        {
            this.interstitial.Show();
            interstitialAutoShow = false;
            interstitialState    = AdsState.None;
        }
        else
        {
            //MonoBehaviour.print("Interstitial is not ready yet");
        }
#endif
    }
Example #7
0
        private void UpdateSymbols(AdsState state)
        {
            if (state == TwinCAT.Ads.AdsState.Run)
            {
                logger.LogDebug($"Update symbols on beckhoff change to {state}");

                var loader = SymbolLoaderFactory.Create(Client, new SymbolLoaderSettings(SymbolsLoadMode.Flat));
                symbolsSubject.OnNext(loader.Symbols);
            }
            else
            {
                logger.LogDebug($"Deleting symbols on beckhoff state change to {state}");
                symbolsSubject.OnNext(null);
            }
        }
Example #8
0
        public AdsErrorCode AdsWriteControlReq(AmsAddress rAddr, uint invokeId, AdsState adsState, ushort deviceState, uint cbLength, byte[] data)
        {
            TcAdsWriteControlReqHeader adsHeader = new TcAdsWriteControlReqHeader {
                _adsState    = adsState,
                _deviceState = deviceState,
                _cbLength    = cbLength
            };
            uint length = 0;

            if (data != null)
            {
                length = (uint)data.Length;
            }
            return(this.AdsRequest(rAddr, invokeId, 5, length, adsHeader, data));
        }
Example #9
0
        protected override unsafe AdsErrorCode WriteControl(AdsState adsState, short deviceState, int length, void *data, bool throwAdsException)
        {
            byte[]       buffer;
            AdsErrorCode noError = AdsErrorCode.NoError;

            if (((buffer = AmsAddressMarshaller.Marshal(base.address)) == null) || (buffer.Length == 0))
            {
                numRef = null;
            }
            else
            {
                numRef = buffer;
            }
            noError = TcAdsDllWrapper.UnsafeNativeMethods.AdsSyncWriteControlReqEx(base._port, numRef, adsState, deviceState, length, data);
            fixed(byte *numRef = null)
            {
                base.OnHandleCommunicationResult(noError, throwAdsException);
                return(noError);
            }
        }
Example #10
0
        public async Task TestSoftBhf()
        {
            IPAddress plcIpAddress = IPAddress.Parse(_plcIpAddress);
            IPAddress localhost    = IPAddress.Parse(_localhostIp);

            RouteInfo info = new RouteInfo();

            info.Localhost        = localhost.ToString();
            info.LocalAmsNetId    = new AdsNetId(_localAsmNetId);
            info.IsTemporaryRoute = false;
            info.Login            = "******";
            info.Password         = "******";

            bool isSuccessful = await RouteManager.AddRemoteRouteAsync(localhost, plcIpAddress, info, 1000);

            Assert.Equal(isSuccessful, true);
            //missing client finder

            using (Socket.AdsClient client = new Socket.AdsClient(
                       amsNetIdSource: _localAsmNetId,
                       ipTarget: _plcIpAddress,
                       amsNetIdTarget: _amsNetIdSource))
            {
                AdsDeviceInfo deviceInfo = await client.ReadDeviceInfoAsync();

                AdsState state = await client.ReadStateAsync();

                client.OnNotification += (sender, e) =>
                {
                    var value = e.Notification.ByteValue;
                    int i     = BitConverter.ToInt32(value, 0);
                    Debug.Write(i);
                };
                uint notification1Handle = await client.AddNotificationAsync <int>(
                    "MAIN.ARRUDICOUNTER[1]", AdsTransmissionMode.OnChange, 1000);

                await Task.Delay(TimeSpan.FromSeconds(10));

                Assert.Equal(true, true);
            }
        }
    public void RequestInterstitial(bool autoShow)
    {
        if (interstitialState == AdsState.Loaded && autoShow)
        {
            ShowInterstitial();
            return;
        }
        else if (interstitialState == AdsState.Loading)
        {
            interstitialAutoShow = autoShow;
            return;
        }
        // These ad units are configured to always serve test ads.
#if UNITY_EDITOR
        string adUnitId = "unused";
#elif UNITY_ANDROID
        string adUnitId = interstitialAndroid;
#elif UNITY_IPHONE
        string adUnitId = interstitialIOS;
#else
        string adUnitId = "unexpected_platform";
#endif
#if UNITY_ANDROID || UNITY_IOS || !EDITOR
        if (this.interstitial == null || !this.interstitial.IsLoaded())
        {
            // Create an interstitial.
            this.interstitial = new InterstitialAd(adUnitId);
            // Register for ad events.
            this.interstitial.OnAdLoaded             += this.HandleInterstitialLoaded;
            this.interstitial.OnAdFailedToLoad       += this.HandleInterstitialFailedToLoad;
            this.interstitial.OnAdOpening            += this.HandleInterstitialOpened;
            this.interstitial.OnAdClosed             += this.HandleInterstitialClosed;
            this.interstitial.OnAdLeavingApplication += this.HandleInterstitialLeftApplication;
            // Load an interstitial ad.
            this.interstitial.LoadAd(adRequest);
            interstitialState = AdsState.Loading;
        }
#endif
        interstitialAutoShow = autoShow;
    }
Example #12
0
        /// <summary>
        /// Connect to PLC
        /// </summary>
        public void Connect()
        {
            // If already connected, disconnect first
            if (Session != null && Connection.ConnectionState == ConnectionState.Connected)
            {
                Disconnect();
            }

            try
            {
                Session?.Dispose();
                Session    = new AdsSession(new AmsAddress(_address), SessionSettings.Default);
                Connection = (AdsConnection)Session.Connect();

                _symbolLoader = SymbolLoaderFactory.Create(Connection, _symbolLoaderSettings);

                StateInfo stateInfo = Connection.ReadState();
                AdsState  state     = stateInfo.AdsState;
                if (state == AdsState.Run || state == AdsState.Stop)
                {
                    Connected = true;
                    GetSymbols();
                }
                else
                {
                    Disconnect();
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                string port = Session == null ? string.Empty : $"Port {Session.Port}: ";
                OnPlcConnectionError(new PlcConnectionErrorEventArgs($"{port}{ex.Message}"));
                Disconnect();
            }
        }
 public void HandleNativeExpressAdLoaded(object sender, EventArgs args)
 {
     print("Native express: Đã load xong");
     nativeState = AdsState.Loaded;
 }
Example #14
0
 public virtual void AdsWriteControlInd(AmsAddress rAddr, uint invokeId, AdsState adsState, ushort deviceState, uint cbLength, byte[] pDeviceData)
 {
     this.AdsWriteControlRes(rAddr, invokeId, AdsErrorCode.DeviceServiceNotSupported);
 }
Example #15
0
        public AdsErrorCode AdsReadStateRes(AmsAddress rAddr, uint invokeId, AdsErrorCode result, AdsState adsState, ushort deviceState)
        {
            TcAdsReadStateResHeader adsHeader = new TcAdsReadStateResHeader {
                _result      = result,
                _adsState    = (ushort)adsState,
                _deviceState = deviceState
            };

            return(this.AdsResponse(rAddr, invokeId, 4, 0, adsHeader, null));
        }
Example #16
0
        private void OnAmsReceive(TcAmsCommand amsCmd)
        {
            byte[] data            = amsCmd.Data;
            uint   indexGroup      = 0;
            uint   cbLength        = 0;
            uint   cbWriteLength   = 0;
            uint   numStampHeaders = 0;

            if (amsCmd.AmsHeader.StateFlags != 4)
            {
                if (amsCmd.AmsHeader.StateFlags == 5)
                {
                    AdsErrorCode code;
                    switch (amsCmd.AmsHeader.CommandId)
                    {
                    case 1:
                    {
                        AdsVersion version = new AdsVersion();
                        if (amsCmd.AmsHeader.ErrCode != 0)
                        {
                            this.AdsReadDeviceInfoCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, (AdsErrorCode)amsCmd.AmsHeader.ErrCode, null, version);
                            return;
                        }
                        code             = (AdsErrorCode)TcAdsParser.ReadUInt(data, 0);
                        version.Version  = data[4];
                        version.Revision = data[5];
                        version.Build    = TcAdsParser.ReadUShort(data, 6);
                        this.AdsReadDeviceInfoCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, code, TcAdsParser.ReadString(data, 8, 0x10), version);
                        return;
                    }

                    case 2:
                        if (amsCmd.AmsHeader.ErrCode != 0)
                        {
                            this.AdsReadCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, (AdsErrorCode)amsCmd.AmsHeader.ErrCode, 0, null);
                            return;
                        }
                        code     = (AdsErrorCode)TcAdsParser.ReadUInt(data, 0);
                        cbLength = TcAdsParser.ReadUInt(data, 4);
                        this.AdsReadCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, code, cbLength, TcAdsParser.AdsData(data, 8, cbLength));
                        return;

                    case 3:
                        if (amsCmd.AmsHeader.ErrCode != 0)
                        {
                            this.AdsWriteCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, (AdsErrorCode)amsCmd.AmsHeader.ErrCode);
                            return;
                        }
                        code = (AdsErrorCode)TcAdsParser.ReadUInt(data, 0);
                        this.AdsWriteCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, code);
                        return;

                    case 4:
                        if (amsCmd.AmsHeader.ErrCode != 0)
                        {
                            this.AdsReadStateCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, (AdsErrorCode)amsCmd.AmsHeader.ErrCode, AdsState.Invalid, 0);
                            return;
                        }
                        code = (AdsErrorCode)TcAdsParser.ReadUInt(data, 0);
                        this.AdsReadStateCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, code, (AdsState)((short)TcAdsParser.ReadUShort(data, 4)), TcAdsParser.ReadUShort(data, 6));
                        return;

                    case 5:
                        if (amsCmd.AmsHeader.ErrCode != 0)
                        {
                            this.AdsWriteControlCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, (AdsErrorCode)amsCmd.AmsHeader.ErrCode);
                            return;
                        }
                        code = (AdsErrorCode)TcAdsParser.ReadUInt(data, 0);
                        this.AdsWriteControlCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, code);
                        return;

                    case 6:
                        if (amsCmd.AmsHeader.ErrCode != 0)
                        {
                            this.AdsAddDeviceNotificationCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, (AdsErrorCode)amsCmd.AmsHeader.ErrCode, 0);
                            return;
                        }
                        code = (AdsErrorCode)TcAdsParser.ReadUInt(data, 0);
                        this.AdsAddDeviceNotificationCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, code, TcAdsParser.ReadUInt(data, 4));
                        return;

                    case 7:
                        if (amsCmd.AmsHeader.ErrCode != 0)
                        {
                            this.AdsDelDeviceNotificationCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, (AdsErrorCode)amsCmd.AmsHeader.ErrCode);
                            return;
                        }
                        code = (AdsErrorCode)TcAdsParser.ReadUInt(data, 0);
                        this.AdsDelDeviceNotificationCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, code);
                        return;

                    case 8:
                        break;

                    case 9:
                        if (amsCmd.AmsHeader.ErrCode != 0)
                        {
                            this.AdsReadWriteCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, (AdsErrorCode)amsCmd.AmsHeader.ErrCode, 0, null);
                            break;
                        }
                        code     = (AdsErrorCode)TcAdsParser.ReadUInt(data, 0);
                        cbLength = TcAdsParser.ReadUInt(data, 4);
                        this.AdsReadWriteCon(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, code, cbLength, TcAdsParser.AdsData(data, 8, cbLength));
                        return;

                    default:
                        return;
                    }
                }
            }
            else
            {
                switch (amsCmd.AmsHeader.CommandId)
                {
                case 1:
                    this.AdsReadDeviceInfoInd(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser);
                    return;

                case 2:
                    indexGroup = TcAdsParser.ReadUInt(data, 0);
                    this.AdsReadInd(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, indexGroup, TcAdsParser.ReadUInt(data, 4), TcAdsParser.DataLength(data, 8));
                    return;

                case 3:
                    indexGroup = TcAdsParser.ReadUInt(data, 0);
                    cbLength   = TcAdsParser.DataLength(data, 8);
                    this.AdsWriteInd(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, indexGroup, TcAdsParser.ReadUInt(data, 4), cbLength, TcAdsParser.AdsData(data, 12, cbLength));
                    return;

                case 4:
                    this.AdsReadStateInd(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser);
                    return;

                case 5:
                {
                    AdsState adsState = TcAdsParser.AdsState(data);
                    cbLength = TcAdsParser.DataLength(data, 4);
                    this.AdsWriteControlInd(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, adsState, TcAdsParser.ReadUShort(data, 2), cbLength, TcAdsParser.AdsData(data, 8, cbLength));
                    return;
                }

                case 6:
                    indexGroup = TcAdsParser.ReadUInt(data, 0);
                    this.AdsAddDeviceNotificationInd(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, indexGroup, TcAdsParser.ReadUInt(data, 4), TcAdsParser.DataLength(data, 8), (AdsTransMode)TcAdsParser.ReadUInt(data, 12), TcAdsParser.ReadUInt(data, 0x10), TcAdsParser.ReadUInt(data, 20));
                    return;

                case 7:
                {
                    uint hNotification = TcAdsParser.ReadUInt(data, 0);
                    this.AdsDelDeviceNotificationInd(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, hNotification);
                    return;
                }

                case 8:
                    if (!this._useSingleNotificationEventHandler)
                    {
                        goto TR_0008;
                    }
                    else
                    {
                        using (AdsBinaryReader reader = new AdsBinaryReader(new AdsStream(data)))
                        {
                            cbLength        = reader.ReadUInt32();
                            numStampHeaders = reader.ReadUInt32();
                            this.AdsDeviceNotificationInd(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, numStampHeaders, reader);
                            break;
                        }
                        goto TR_0008;
                    }
                    break;

                case 9:
                    indexGroup    = TcAdsParser.ReadUInt(data, 0);
                    cbWriteLength = TcAdsParser.ReadUInt(data, 12);
                    this.AdsReadWriteInd(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, indexGroup, TcAdsParser.ReadUInt(data, 4), TcAdsParser.ReadUInt(data, 8), cbWriteLength, TcAdsParser.AdsData(data, 0x10, cbWriteLength));
                    return;

                default:
                    return;
                }
            }
            return;

TR_0008:
            cbLength        = TcAdsParser.ReadUInt(data, 0);
            numStampHeaders = TcAdsParser.ReadUInt(data, 4);
            this.AdsDeviceNotificationInd(amsCmd.AmsHeader.Sender, amsCmd.AmsHeader.HUser, numStampHeaders, TcAdsParser.ReadNotificationStampHeaders(data, numStampHeaders));
        }
Example #17
0
        static void Main(string[] args)
        {
            bool showHelp = false;
            bool enableDebugLoggingLevel = false;

            Console.CancelKeyPress += new ConsoleCancelEventHandler(CancelKeyPressHandler);
            log4net.GlobalContext.Properties["LogLocation"] = AppDomain.CurrentDomain.BaseDirectory + "\\logs";
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));

            OptionSet options = new OptionSet()
                                .Add("v=|VisualStudioSolutionFilePath=", "The full path to the TwinCAT project (sln-file)", v => VisualStudioSolutionFilePath = v)
                                .Add("t=|TcUnitTaskName=", "[OPTIONAL] The name of the task running TcUnit defined under \"Tasks\"", t => TcUnitTaskName      = t)
                                .Add("a=|AmsNetId=", "[OPTIONAL] The AMS NetId of the device of where the project and TcUnit should run", a => AmsNetId       = a)
                                .Add("w=|TcVersion=", "[OPTIONAL] The TwinCAT version to be used to load the TwinCAT project", w => ForceToThisTwinCATVersion = w)
                                .Add("u=|Timeout=", "[OPTIONAL] Timeout the process with an error after X minutes", u => Timeout = u)
                                .Add("d|debug", "[OPTIONAL] Increase debug message verbosity", d => enableDebugLoggingLevel      = d != null)
                                .Add("?|h|help", h => showHelp = h != null);

            try
            {
                options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `TcUnit-Runner --help' for more information.");
                Environment.Exit(Constants.RETURN_ARGUMENT_ERROR);
            }


            if (showHelp)
            {
                DisplayHelp(options);
                Environment.Exit(Constants.RETURN_SUCCESSFULL);
            }

            /* Set logging level.
             * This is handled by changing the log4net.config file on the fly.
             * The following levels are defined in order of increasing priority:
             * - ALL
             * - DEBUG
             * - INFO
             * - WARN
             * - ERROR
             * - FATAL
             * - OFF
             */
            XmlDocument doc = new XmlDocument();

            doc.Load(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");
            XmlNode root          = doc.DocumentElement;
            XmlNode subNode1      = root.SelectSingleNode("root");
            XmlNode nodeForModify = subNode1.SelectSingleNode("level");

            if (enableDebugLoggingLevel)
            {
                nodeForModify.Attributes[0].Value = "DEBUG";
            }
            else
            {
                nodeForModify.Attributes[0].Value = "INFO";
            }
            doc.Save(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");
            System.Threading.Thread.Sleep(500); // A tiny sleep just to make sure that log4net manages to detect the change in the file

            /* Make sure the user has supplied the path for the Visual Studio solution file.
             * Also verify that this file exists.
             */
            if (VisualStudioSolutionFilePath == null)
            {
                log.Error("Visual studio solution path not provided!");
                Environment.Exit(Constants.RETURN_VISUAL_STUDIO_SOLUTION_PATH_NOT_PROVIDED);
            }

            if (!File.Exists(VisualStudioSolutionFilePath))
            {
                log.Error("Visual studio solution " + VisualStudioSolutionFilePath + " does not exist!");
                Environment.Exit(Constants.RETURN_VISUAL_STUDIO_SOLUTION_PATH_NOT_FOUND);
            }

            LogBasicInfo();

            /* Start a timeout for the process(es) if the user asked for it
             */
            if (Timeout != null)
            {
                log.Info("Timeout enabled - process(es) timesout after " + Timeout + " minute(s)");
                System.Timers.Timer timeout = new System.Timers.Timer(Int32.Parse(Timeout) * 1000 * 60);
                timeout.Elapsed  += KillProcess;
                timeout.AutoReset = false;
                timeout.Start();
            }

            MessageFilter.Register();

            TwinCATProjectFilePath = TcFileUtilities.FindTwinCATProjectFile(VisualStudioSolutionFilePath);
            if (String.IsNullOrEmpty(TwinCATProjectFilePath))
            {
                log.Error("Did not find TwinCAT project file in solution. Is this a TwinCAT project?");
                Environment.Exit(Constants.RETURN_TWINCAT_PROJECT_FILE_NOT_FOUND);
            }

            if (!File.Exists(TwinCATProjectFilePath))
            {
                log.Error("TwinCAT project file " + TwinCATProjectFilePath + " does not exist!");
                Environment.Exit(Constants.RETURN_TWINCAT_PROJECT_FILE_NOT_FOUND);
            }

            string tcVersion = TcFileUtilities.GetTcVersion(TwinCATProjectFilePath);

            if (String.IsNullOrEmpty(tcVersion))
            {
                log.Error("Did not find TwinCAT version in TwinCAT project file path");
                Environment.Exit(Constants.RETURN_TWINCAT_VERSION_NOT_FOUND);
            }

            try
            {
                vsInstance = new VisualStudioInstance(@VisualStudioSolutionFilePath, tcVersion, ForceToThisTwinCATVersion);
                bool isTcVersionPinned = XmlUtilities.IsTwinCATProjectPinned(TwinCATProjectFilePath);
                log.Info("Version is pinned: " + isTcVersionPinned);
                vsInstance.Load(isTcVersionPinned);
            }
            catch
            {
                log.Error("Error loading VS DTE. Is the correct version of Visual Studio and TwinCAT installed? Is the TcUnit-Runner running with administrator privileges?");
                CleanUpAndExitApplication(Constants.RETURN_ERROR_LOADING_VISUAL_STUDIO_DTE);
            }

            try
            {
                vsInstance.LoadSolution();
            }
            catch
            {
                log.Error("Error loading the solution. Try to open it manually and make sure it's possible to open and that all dependencies are working");
                CleanUpAndExitApplication(Constants.RETURN_ERROR_LOADING_VISUAL_STUDIO_SOLUTION);
            }

            if (vsInstance.GetVisualStudioVersion() == null)
            {
                log.Error("Did not find Visual Studio version in Visual Studio solution file");
                CleanUpAndExitApplication(Constants.RETURN_ERROR_FINDING_VISUAL_STUDIO_SOLUTION_VERSION);
            }


            AutomationInterface automationInterface = new AutomationInterface(vsInstance.GetProject());

            if (automationInterface.PlcTreeItem.ChildCount <= 0)
            {
                log.Error("No PLC-project exists in TwinCAT project");
                CleanUpAndExitApplication(Constants.RETURN_NO_PLC_PROJECT_IN_TWINCAT_PROJECT);
            }


            ITcSmTreeItem realTimeTasksTreeItem = automationInterface.RealTimeTasksTreeItem;

            /* Task name provided */
            if (!String.IsNullOrEmpty(TcUnitTaskName))
            {
                log.Info("Setting task '" + TcUnitTaskName + "' enable and autostart, and all other tasks (if existing) to disable and non-autostart");
                bool foundTcUnitTaskName = false;

                /* Find all tasks, and check whether the user provided TcUnit task is amongst them.
                 * Also update the task object (Update <Disabled> and <Autostart>-tag)
                 */
                foreach (ITcSmTreeItem child in realTimeTasksTreeItem)
                {
                    ITcSmTreeItem testTreeItem = realTimeTasksTreeItem.LookupChild(child.Name);
                    string        xmlString    = testTreeItem.ProduceXml();
                    string        newXmlString = "";
                    try
                    {
                        if (TcUnitTaskName.Equals(XmlUtilities.GetItemNameFromRealTimeTaskXML(xmlString)))
                        {
                            foundTcUnitTaskName = true;
                            newXmlString        = XmlUtilities.SetDisabledAndAndAutoStartOfRealTimeTaskXml(xmlString, false, true);
                        }
                        else
                        {
                            newXmlString = XmlUtilities.SetDisabledAndAndAutoStartOfRealTimeTaskXml(xmlString, true, false);
                        }
                        testTreeItem.ConsumeXml(newXmlString);
                        System.Threading.Thread.Sleep(3000);
                    }
                    catch
                    {
                        log.Error("Could not parse real time task XML data");
                        CleanUpAndExitApplication(Constants.RETURN_NOT_POSSIBLE_TO_PARSE_REAL_TIME_TASK_XML_DATA);
                    }
                }

                if (!foundTcUnitTaskName)
                {
                    log.Error("Could not find task '" + TcUnitTaskName + "' in TwinCAT project");
                    CleanUpAndExitApplication(Constants.RETURN_FAILED_FINDING_DEFINED_UNIT_TEST_TASK_IN_TWINCAT_PROJECT);
                }
            }

            /* No task name provided */
            else
            {
                log.Info("No task name provided. Assuming only one task exists");
                /* Check that only one task exists */
                if (realTimeTasksTreeItem.ChildCount.Equals(1))
                {
                    // Get task name
                    ITcSmTreeItem child        = realTimeTasksTreeItem.get_Child(1);
                    ITcSmTreeItem testTreeItem = realTimeTasksTreeItem.LookupChild(child.Name);
                    string        xmlString    = testTreeItem.ProduceXml();
                    TcUnitTaskName = XmlUtilities.GetItemNameFromRealTimeTaskXML(xmlString);
                    log.Info("Found task with name '" + TcUnitTaskName + "'");
                    string newXmlString = "";
                    newXmlString = XmlUtilities.SetDisabledAndAndAutoStartOfRealTimeTaskXml(xmlString, false, true);
                    testTreeItem.ConsumeXml(newXmlString);
                    System.Threading.Thread.Sleep(3000);
                }
                /* Less ore more than one task, which is an error */
                else
                {
                    log.Error("The number of tasks is not equal to 1 (one). Found " + realTimeTasksTreeItem.ChildCount.ToString() + " number of tasks. Please provide which task is the TcUnit task");
                    CleanUpAndExitApplication(Constants.RETURN_TASK_COUNT_NOT_EQUAL_TO_ONE);
                }
            }


            /* Build the solution and collect any eventual errors. Make sure to
             * filter out everything that is an error
             */
            vsInstance.CleanSolution();
            vsInstance.BuildSolution();

            ErrorItems errorsBuild = vsInstance.GetErrorItems();

            int tcBuildWarnings = 0;
            int tcBuildError    = 0;

            for (int i = 1; i <= errorsBuild.Count; i++)
            {
                ErrorItem item = errorsBuild.Item(i);
                if ((item.ErrorLevel != vsBuildErrorLevel.vsBuildErrorLevelLow))
                {
                    if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelMedium)
                    {
                        tcBuildWarnings++;
                    }
                    else if (item.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh)
                    {
                        tcBuildError++;
                        log.Error("Description: " + item.Description);
                        log.Error("ErrorLevel: " + item.ErrorLevel);
                        log.Error("Filename: " + item.FileName);
                    }
                }
            }

            /* If we don't have any errors, activate the configuration and
             * start/restart TwinCAT */
            if (tcBuildError.Equals(0))
            {
                /* Check whether the user has provided an AMS NetId. If so, use it. Otherwise use
                 * the local AMS NetId */
                if (String.IsNullOrEmpty(AmsNetId))
                {
                    AmsNetId = Constants.LOCAL_AMS_NET_ID;
                }

                log.Info("Setting target NetId to '" + AmsNetId + "'");
                automationInterface.ITcSysManager.SetTargetNetId(AmsNetId);
                log.Info("Enabling boot project and setting BootProjectAutostart on " + automationInterface.ITcSysManager.GetTargetNetId());

                for (int i = 1; i <= automationInterface.PlcTreeItem.ChildCount; i++)
                {
                    ITcSmTreeItem plcProject = automationInterface.PlcTreeItem.Child[i];
                    ITcPlcProject iecProject = (ITcPlcProject)plcProject;
                    iecProject.BootProjectAutostart = true;

                    /* add the port that is used for this PLC to the AmsPorts list that
                     * is later used to monitory the AdsState
                     */
                    string xmlString = plcProject.ProduceXml();
                    AmsPorts.Add(XmlUtilities.AmsPort(xmlString));
                }
                System.Threading.Thread.Sleep(1000);
                automationInterface.ActivateConfiguration();

                // Wait
                System.Threading.Thread.Sleep(10000);

                /* Clean the solution. This is the only way to clean the error list which needs to be
                 * clean prior to starting the TwinCAT runtime */
                vsInstance.CleanSolution();

                // Wait
                System.Threading.Thread.Sleep(10000);

                automationInterface.StartRestartTwinCAT();
            }
            else
            {
                log.Error("Build errors in project");
                CleanUpAndExitApplication(Constants.RETURN_BUILD_ERROR);
            }

            /* Establish a connection to the ADS router
             */
            TcAdsClient tcAdsClient = new TcAdsClient();

            /* Run TcUnit until the results have been returned */
            TcUnitResultCollector tcUnitResultCollector = new TcUnitResultCollector();
            ErrorList             errorList             = new ErrorList();

            log.Info("Waiting for results from TcUnit...");

            ErrorItems errorItems;

            while (true)
            {
                System.Threading.Thread.Sleep(10000);

                /* Monitor the AdsState for each PLC that is used in the
                 * solution. If we can't connect to the Ads Router, we just
                 * carry on.
                 */
                try
                {
                    foreach (int amsPort in AmsPorts)
                    {
                        tcAdsClient.Connect(AmsNetId, amsPort);
                        AdsState adsState = tcAdsClient.ReadState().AdsState;
                        if (adsState != AdsState.Run)
                        {
                            log.Error("Invalid AdsState " + adsState + "<>" + AdsState.Run + ". This could indicate a PLC Exception, terminating ...");
                            Environment.Exit(Constants.RETURN_INVALID_ADSSTATE);
                        }
                    }
                }
                catch (Exception ex)
                { }
                finally
                {
                    tcAdsClient.Disconnect();
                }

                errorItems = vsInstance.GetErrorItems();

                var newErrors = errorList.AddNew(errorItems);
                if (log.IsDebugEnabled)
                {
                    foreach (var error in newErrors)
                    {
                        log.Debug(error.ErrorLevel + ": " + error.Description);
                    }
                }

                log.Info("... got " + errorItems.Count + " report lines so far.");
                if (tcUnitResultCollector.AreResultsAvailable(errorItems))
                {
                    log.Info("All results from TcUnit obtained");

                    /* The last test suite result can be returned after that we have received the test results, wait a few seconds
                     * and fetch again
                     */
                    System.Threading.Thread.Sleep(10000);
                    break;
                }
            }

            List <ErrorList.Error> errors       = new List <ErrorList.Error>(errorList.Where(e => (e.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelHigh || e.ErrorLevel == vsBuildErrorLevel.vsBuildErrorLevelLow)));
            List <ErrorList.Error> errorsSorted = errors.OrderBy(o => o.Description).ToList();

            /* Parse all events (from the error list) from Visual Studio and store the results */
            TcUnitTestResult testResult = tcUnitResultCollector.ParseResults(errorsSorted, TcUnitTaskName);

            /* Write xUnit XML report */
            if (testResult != null)
            {
                // No need to check if file (VisualStudioSolutionFilePath) exists, as this has already been done
                string VisualStudioSolutionDirectoryPath = Path.GetDirectoryName(VisualStudioSolutionFilePath);
                string XUnitReportFilePath = VisualStudioSolutionDirectoryPath + "\\" + Constants.XUNIT_RESULT_FILE_NAME;
                log.Info("Writing xUnit XML file to " + XUnitReportFilePath);
                // Overwrites all existing content (if existing)
                XunitXmlCreator.WriteXml(testResult, XUnitReportFilePath);
            }

            CleanUpAndExitApplication(Constants.RETURN_SUCCESSFULL);
        }
        private void DisplayPlcState(AdsState state)
        {
            switch (state)
            {
            case AdsState.Invalid:
                UpdateDumpStatus("PLC state: Invalid", Colors.Red);
                break;

            case AdsState.Idle:
                UpdateDumpStatus("PLC state: Idle", Colors.Orange);
                break;

            case AdsState.Reset:
                UpdateDumpStatus("PLC state: Reset", Colors.Orange);
                break;

            case AdsState.Init:
                UpdateDumpStatus("PLC state: Init", Colors.Orange);
                break;

            case AdsState.Start:
                UpdateDumpStatus("PLC state: Start", Colors.Yellow);
                break;

            case AdsState.Run:
                UpdateDumpStatus("PLC state: Run", Colors.GreenYellow);
                break;

            case AdsState.Stop:
                UpdateDumpStatus("PLC state: Stop", Colors.Orange);
                break;

            case AdsState.SaveConfig:
                UpdateDumpStatus("PLC state: SaveConfig", Colors.Orange);
                break;

            case AdsState.LoadConfig:
                UpdateDumpStatus("PLC state: LoadConfig", Colors.Orange);
                break;

            case AdsState.PowerFailure:
                UpdateDumpStatus("PLC state: PowerFailure", Colors.Orange);
                break;

            case AdsState.PowerGood:
                UpdateDumpStatus("PLC state: PowerGood", Colors.Orange);
                break;

            case AdsState.Error:
                UpdateDumpStatus("PLC state: Error", Colors.Orange);
                break;

            case AdsState.Shutdown:
                UpdateDumpStatus("PLC state: Shutdown", Colors.Orange);
                break;

            case AdsState.Suspend:
                UpdateDumpStatus("PLC state: Suspend", Colors.Orange);
                break;

            case AdsState.Resume:
                UpdateDumpStatus("PLC state: Resume", Colors.Orange);
                break;

            case AdsState.Config:
                UpdateDumpStatus("PLC state: Config", Colors.Orange);
                break;

            case AdsState.Reconfig:
                UpdateDumpStatus("PLC state: Reconfig", Colors.Orange);
                break;

            case AdsState.Stopping:
                UpdateDumpStatus("PLC state: Stopping", Colors.Orange);
                break;

            case AdsState.Incompatible:
                UpdateDumpStatus("PLC state: Incompatible", Colors.Red);
                break;

            case AdsState.Exception:
                UpdateDumpStatus("PLC state: Exception", Colors.Red);
                break;

            default:
                Debug.WriteLine(state);
                break;
            }
        }
Example #19
0
 protected override void AdsResponseIsChanged()
 {
     adsState             = new AdsState();
     adsState.State       = BitConverter.ToUInt16(this.AdsResponse, 4);
     adsState.DeviceState = BitConverter.ToUInt16(this.AdsResponse, 6);
 }
 public void HandleRewardBasedVideoFailedToLoad(object sender, AdFailedToLoadEventArgs args)
 {
     print("Reward Based Video: Load lỗi");
     rewardState = AdsState.Error;
     this.callBack(false);
 }
 public void HandleInterstitialFailedToLoad(object sender, AdFailedToLoadEventArgs args)
 {
     print("Interstitial: Load lỗi");
     interstitialState = AdsState.Error;
 }
 public void HandleNativeExpressAdOpened(object sender, EventArgs args)
 {
     print("Native express: Đã show");
     nativeState = AdsState.None;
 }
 public void HandleNativeExpresseAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
 {
     print("Native express: Load lỗi");
     nativeState = AdsState.Error;
 }
Example #24
0
 public virtual void AdsReadStateCon(AmsAddress rAddr, uint invokeId, AdsErrorCode result, AdsState adsState, ushort deviceState)
 {
 }