Пример #1
0
		public static void Main (string[] args)
		{
			ButtonEvents buts = new ButtonEvents ();
			var tokenSource = new CancellationTokenSource();
      		var token = tokenSource.Token;

			var dialog = new InfoDialog("Attach distance sensor", false);
			dialog.Show();
			var sensor = SensorAttachment.Wait<MSAngleSensor>(token);//wait for sensor to attached on any port
			LcdConsole.WriteLine("Up reset angle");
			LcdConsole.WriteLine("Down read RMP");
			LcdConsole.WriteLine("Enter read angle");
			LcdConsole.WriteLine("Left read raw");
			LcdConsole.WriteLine("Esc. terminate");

			buts.EscapePressed += () => { 
				tokenSource.Cancel();
			};
			buts.EnterPressed += () => {
				LcdConsole.WriteLine ("Angle: " + sensor.ReadAngle().ToString());
			};
			buts.UpPressed += () => { 
				LcdConsole.WriteLine ("Reset angle");
				sensor.ResetAngle();
			};
			buts.DownPressed += () => { 
				LcdConsole.WriteLine ("Read RPM: " +  sensor.ReadRPM().ToString());
			};
			buts.LeftPressed += () => { 
				LcdConsole.WriteLine ("Read raw: " +  sensor.ReadRAW().ToString());
			};
			token.WaitHandle.WaitOne();
		}
Пример #2
0
 public static void Main(string[] args)
 {
     InfoDialog dialog = new InfoDialog ("Attach a motor to port A", true);
     dialog.Show ();//Wait for enter to be pressed
     Motor motor = new Motor (MotorPort.OutA);
     motor.SetSpeed (50);
     Thread.Sleep (3000);
     motor.Off ();
     Lcd.Instance.Clear ();
 }
Пример #3
0
		static void Main (string[] args)
		{
			var step = new StepContainer (StartWebserver, "Starting server", "Failed to start");
			Dialog dialog = new ProgressDialog("Webserver", step);
			if (dialog.Show ()) {
				dialog = new InfoDialog ("Press enter to stop", true, "Webserver");
				dialog.Show ();
				StopWebserver ();
			}
			
		}
Пример #4
0
		const int REMOTE_COMMAND_STOP  = 's'; // 's'

		public static void Main()
		{
			// 構造体の宣言と初期化
			var body = new EV3body ();
			EV3body.init (ref body);

			// Bluetooth関係のETロボコン拡張機能を有効にする
			Brick.InstallETRoboExt ();
		
			// リモート接続
			NetworkStream connection = connect();

			// センサーおよびモータに対して初回アクセスをしておく
			body.color.Read();
			body.sonar.Read();
			body.gyro.Read ();
			body.motorL.SetPower (0);
			body.motorR.SetPower (0);
			body.motorT.SetPower (0);

			body.motorL.ResetTacho ();
			body.motorR.ResetTacho ();
			body.motorT.ResetTacho ();
			Balancer.init ();

			// スタート待ち
			wait_start(body, connection);

			var dialogRun = new InfoDialog ("Running", false);
			dialogRun.Show ();//Wait for enter to be pressed

			try{
				run(body, connection);
			}catch(Exception){
				var dialogE = new InfoDialog ("Exception.", false);
				dialogE.Show();//Wait for enter to be pressed
			}

			body.motorL.Off ();
			body.motorR.Off ();
			body.motorT.Off ();

			// ソケットを閉じる
			if (connection != null) {
				connection.Close ();
			}

			Lcd.Instance.Clear ();
			Lcd.Instance.Update ();

			if (Debugger.IsAttached) {
				Brick.ExitToMenu (); // MonoBrickメインメニューへ戻る
			}
		}
Пример #5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="body"></param>
        public void wait_start(EquipmentParameters body)
        {
            //スタート待ち
            var dialogSTART = new InfoDialog("Touch to START", false);
            dialogSTART.Show(); // Wait for enter to be pressed

            MicroStopwatch stopwatch = new MicroStopwatch();
            stopwatch.Start();
            int counter = 0;
            Thread.Sleep(2000);

            while (!body.TouchSensors.IsPressed())
            {
                TailMoter.tailControl(body, EquipmentParameters.TAIL_ANGLE_STAND_UP); //完全停止用角度に制御
                if (btConnectionLibrary.CheckRemoteCommand(EquipmentParameters.REMOTE_COMMAND_START))
                    break;  // PC で 'g' キーが押された

                // 電圧を取得
                int battery = Brick.GetVoltageMilliVolt();
                int reflection = body.LightSensors.Read();
                int gyroNow = body.GyroSensors.Read();
                int thetaL = body.MpLeft.GetTachoCount();
                int theTaR = body.MpRight.GetTachoCount();
                
                SensorData sendData = new SensorData();
                sendData.AddAPower(builder, 0);
                sendData.AddBPower(builder, 0);
                sendData.AddBOdometer(builder, thetaL);
                sendData.AddBattery(builder, battery);
                sendData.AddCPower (builder, 0);
                sendData.AddCOdometer (builder, theTaR);
                sendData.AddGyroSensor(builder, gyroNow);
                sendData.AddReflectionSensor(builder, reflection);
                sendData.AddSonerSensor(builder, 0);
                sendData.AddTouchSenser(builder, 0);
                sendData.AddTaskProcessTime(builder, stopwatch.ElapsedMicroseconds);
                btConnectionLibrary.SensorDataContainer.Enqueue(sendData);

                if (++counter >= 100 / 4)
                {

                     btConnectionLibrary.SendQueueData2();
                     counter = 0;
                }

                Thread.Sleep(4);
            }

            while (body.TouchSensors.IsPressed())
            {
                TailMoter.tailControl(body, EquipmentParameters.TAIL_ANGLE_STAND_UP); //完全停止用角度に制御
                Thread.Sleep(4);
            }
        }
Пример #6
0
        /// <summary>
        /// 接続処理
        /// </summary>
        /// <returns></returns>
        public bool Connect()
        {
            bool isConnect = false;
            // サーバとの接続設定
            IPAddress ipAddr = IPAddress.Parse(IpAddress);

            var listener = new TcpListener(ipAddr, EquipmentParameters.SOCKET_PORT);
            listener.Start(); // クライアントからの受信接続要求の待機を開始

            var dialogCON = new InfoDialog("Please connect...", false);
            dialogCON.Show(); // Wait for enter to be pressed

            try
            {
                Socket sock = listener.AcceptSocket(); // 接続要求の受け入れ

                var dialogCONA = new InfoDialog("AcceptSocket...", false);
                dialogCONA.Show(); // Wait for enter to be pressed

                Connection = new NetworkStream(sock, true);

                var dialogCONB = new InfoDialog("NetworkStream...", false);
                dialogCONB.Show(); // Wait for enter to be pressed

                isConnect = true;
            }
            catch (InvalidOperationException)
            {
                var dialogE = new InfoDialog("Connect is Failed1.", false);
                dialogE.Show(); // Wait for enter to be pressed
                Connection = null;
            }
            catch (IOException)
            {
                var dialogE = new InfoDialog("Connect is Failed2.", false);
                dialogE.Show(); // Wait for enter to be pressed
                Connection = null;
            }
            catch (SocketException)
            {
                var dialogE = new InfoDialog("Connect is Failed3.", false);
                dialogE.Show(); // Wait for enter to be pressed
                Connection = null;
            }

            var dialogCON2 = new InfoDialog("Listener connected.", false);
            dialogCON2.Show(); // Wait for enter to be pressed

            listener.Stop();
            return isConnect;
        }
Пример #7
0
		public static bool TurnCheckBoxOnOff (bool isChecked)
		{
			if (isChecked) {
				var step = new StepContainer (DummyStep, "Turning off", "Failed to turn off");
				var progressDialog = new ProgressDialog ("Information", step);
				progressDialog.Show ();
				return false;
			} 
			else 
			{
				var dialog = new InfoDialog("Turning On", true);
				dialog.Show();
				return true;
			}
		}
Пример #8
0
		private void OnUpdateCompleted(StepDialog dialog)
		{
			if (dialog.ExecutedOk)
			{
				Parent.SuspendButtonEvents ();
				Lcd.Clear ();
				Lcd.WriteText (Font.MediumFont, new Point (0, 0), "Shutting down...", true);
				Lcd.Update ();
				Buttons.LedPattern (2);
				Brick.TurnOff ();
				var whyAreYouHereDialog = new InfoDialog ("Cut the power", "Reboot failed");
				whyAreYouHereDialog.Show ();
				Lcd.Clear ();
				new ManualResetEvent (false).WaitOne ();
			} 
		}
Пример #9
0
  static void Main(string[] args)
  {
      try
      {
          // AOT Compile
          ProcessHelper.RunAndWaitForProcess(monoPath, "--aot=full " + ProgramPathSdCard + "/" + TargetProgramFolder + "/" + TargetProgramNameEXE);
          ProcessHelper.RunAndWaitForProcess(monoPath, "--aot=full " + ProgramPathSdCard + "/" + TargetProgramFolder + "/" + "MonoBrickFirmware.dll");
          var info = new InfoDialog("AOTCompileApp is Success.", true, "Program");
          info.Show();
      }
      catch
      {
          var info = new InfoDialog("AOTCompileApp is Error.", true, "Program");
          info.Show ();
      }
 }
Пример #10
0
		public static void Main (string[] args)
		{
			using (ButtonEvents buts = new ButtonEvents ()) 
			{
				var tokenSource = new CancellationTokenSource ();
				var token = tokenSource.Token;
				buts.EscapePressed += tokenSource.Cancel;
				var dialog = new InfoDialog ("Attach distance sensor");
				dialog.Show ();
				var sensor = SensorAttachment.Wait<MSDistanceSensor> (token);//wait for sensor to attached on any port
				if (!token.IsCancellationRequested) 
				{
					LcdConsole.WriteLine ("Up power on");
					LcdConsole.WriteLine ("Down power off");
					LcdConsole.WriteLine ("Enter read sensor");
					LcdConsole.WriteLine ("Left read voltage");
					LcdConsole.WriteLine ("Right read range type");
					LcdConsole.WriteLine ("Esc. terminate");


					buts.EnterPressed += () => 
					{
						LcdConsole.WriteLine ("Sensor reading: " + sensor.ReadAsString ());
					};
					buts.UpPressed += () => 
					{ 
						LcdConsole.WriteLine ("Power on");
						sensor.PowerOn ();
					};
					buts.DownPressed += () => 
					{ 
						LcdConsole.WriteLine ("Power off");
						sensor.PowerOff ();
					};
					buts.LeftPressed += () => 
					{ 
						LcdConsole.WriteLine ("Voltage: " + sensor.GetVolgage ());	
					};
					buts.RightPressed += () => 
					{ 
						LcdConsole.WriteLine ("Sensor range is  : " + sensor.GetRange ());	
					};
				}
				token.WaitHandle.WaitOne ();
			}
		}
Пример #11
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var initDialog = new InfoDialog("InitializingDB", false);
            initDialog.Show();//Wait for enter to be pressed
            
            // 処理速度の観点からNG
            //using System.Diagnostics;
            //がソースファイルの一番上に書かれているものとする
            // DefaultTraceListenerオブジェクトを取得
            // DefaultTraceListener drl;
            // drl = (DefaultTraceListener)Trace.Listeners["Default"];
            // LogFileNameを変更する
            // drl.LogFileName = @"home/root/apps/ET2015/test1.txt";
            // drl.LogFileName = @"test1.txt";

            initDialog.UpdateMessage("InitializeingParam");
            initDialog.Show();//Wait for enter to be pressed

            // 構造体の宣言と初期化
            // var body = new EV3body();
            // EV3body.init(ref body);
            var equipParameter = new EquipmentParameters();
            var mainControl = new MainLogic();
            // ログ取得対象のセンサを追加する

            // Bluetooth関係のETロボコン拡張機能を有効にする
            Brick.InstallETRoboExt();

            var btConnectionLibrary = new Bluetooth();

            // リモート接続
            btConnectionLibrary.Connect();
            mainControl.btConnectionLibrary = btConnectionLibrary;

            //キャリブレーション
            equipParameter.GyroSensors.Reset();
			InfoDialog dialogGyro = new InfoDialog ("Calibrate Gyro", false);
			dialogGyro.Show ();//Wait for enter to be pressed
			equipParameter.GyroSensors.Read() + 600;
			//int gyroOff = gyro.ReadAngularAcceleration ();

            // 左・右走行?
            // センサーおよびモータに対して初回アクセスをしておく
            equipParameter.LightSensors.Read();
            equipParameter.DistSensors.Read();
            equipParameter.GyroSensors.Read();
            equipParameter.MpLeft.SetPower(0);
            equipParameter.MpRight.SetPower(0);
            equipParameter.TailMoter.SetPower(0);
            equipParameter.MpLeft.ResetTacho();
            equipParameter.MpRight.ResetTacho();
            equipParameter.TailMoter.ResetTacho();

            Balancer.init();

            // スタート待ち
            // TODO: 処理速度
            mainControl.wait_start(equipParameter);

            try
            {
                mainControl.run(equipParameter);
            }
            catch (Exception)
            {
                var dialogE = new InfoDialog("Exception.", false);
                dialogE.Show();//Wait for enter to be pressed
            }

            equipParameter.MpLeft.Off();
            equipParameter.MpRight.Off();
            equipParameter.TailMoter.Off();

            // ソケットを閉じる
            // if (connection != null)
            // {
            //     connection.Close();
            // }

            Lcd.Instance.Clear();
            Lcd.Instance.Update();

            if (Debugger.IsAttached)
            {
                Brick.ExitToMenu(); // MonoBrickメインメニューへ戻る
            }
        }
Пример #12
0
		static NetworkStream connect(){
			// サーバとの接続設定
			NetworkStream connection;
			IPAddress ipAddr = IPAddress.Parse("10.0.1.1");

			var listener = new TcpListener (ipAddr, SOCKET_PORT); 
			listener.Start(); // クライアントからの受信接続要求の待機を開始

			var dialogCON = new InfoDialog ("Please connect...", false);
			dialogCON.Show(); // Wait for enter to be pressed

			try {
				Socket sock = listener.AcceptSocket(); // 接続要求の受け入れ
				connection = new NetworkStream(sock, true);
			} catch (SocketException) {
				var dialogE = new InfoDialog ("Connect is Failed.", false);
				dialogE.Show(); // Wait for enter to be pressed
				connection = null;
			}
			listener.Stop();
			return connection;
		}
Пример #13
0
		static bool ShowUpdatesDialogs ()
		{
			if (WiFiDevice.IsLinkUp ()) {
				bool newImage = false;
				bool newFirmwareApp = false;
				bool newAddin = false;
				VersionInfo versionInfo = null;
				var step = new StepContainer (
					delegate() {
						try {
							versionInfo = VersionHelper.AvailableVersions ();
							newImage = versionInfo.Image != VersionHelper.CurrentImageVersion ();
							newFirmwareApp = versionInfo.Fimrware != firmwareVersion;
							string addInVersion = VersionHelper.CurrentAddInVersion ();
							if (addInVersion != null)
								newAddin = versionInfo.AddIn != VersionHelper.CurrentAddInVersion ();
						} catch {
							return false;
						}
						return true;
					},
					           "Checking server", "Failed to check for Updates"); 
				var dialog = new ProgressDialog ("Updates", step);
				dialog.Show ();
				if (newImage) {
					var visitWebsiteDialog = new InfoDialog ("New image available. Download it at monobrick.dk", true);
					visitWebsiteDialog.Show ();
				} else {
					if (newFirmwareApp) {
						var updateQuestion = new QuestionDialog ("New firmware available. Update?", "New Fiwmware");
						if (updateQuestion.Show ()) {
							var updateHelper = new UpdateHelper (versionInfo.Fimrware);
							List<IStep> steps = new List<IStep> ();
							steps.Add (new StepContainer (updateHelper.DownloadFirmware, "Downloading...", "Failed to download files"));
							steps.Add (new StepContainer (updateHelper.UpdateBootFile, "Updating system", "Failed to update boot file"));
							var updateDialog = new StepDialog ("Updating", steps);
							if (updateDialog.Show ()) {
								for (int seconds = 10; seconds > 0; seconds--) {
									var rebootDialog = new InfoDialog ("Update completed. Rebooting in  " + seconds, false);
									rebootDialog.Show ();
									System.Threading.Thread.Sleep (1000);
								}
								ProcessHelper.RunAndWaitForProcess ("/sbin/shutdown", "-h now");
								Thread.Sleep (120000);
								var whyAreYouHereDialog = new InfoDialog ("Cut the power", false, "Reboot failed");
								whyAreYouHereDialog.Show ();
								new ManualResetEvent (false).WaitOne ();
							}
						}
					} else {
						if (newAddin) {
							var visitWebsiteDialog = new InfoDialog ("New Xamarin Add-in. Download it at monobrick.dk", true);
							visitWebsiteDialog.Show ();	
						} else 
						{
							var noUpdateDialog = new InfoDialog ("No updates available", true);
							noUpdateDialog.Show ();	
						} 
					}
				}
			} 
			else 
			{
				var dialog = new InfoDialog ("WiFi device is not pressent", true);
				dialog.Show();	
			}
			return false;
		}
Пример #14
0
		static void wait_start(EV3body body, NetworkStream connection){
			//スタート待ち
			var dialogSTART = new InfoDialog ("Touch to START", false);
			dialogSTART.Show (); // Wait for enter to be pressed

			while (!body.touch.IsPressed()) {
				tail_control(body, TAIL_ANGLE_STAND_UP); //完全停止用角度に制御
				if (checkRemoteCommand(connection, REMOTE_COMMAND_START))
					break;  // PC で 'g' キーが押された
				Thread.Sleep (4);
			}

			while (body.touch.IsPressed ()) {
				tail_control(body, TAIL_ANGLE_STAND_UP); //完全停止用角度に制御
				Thread.Sleep (4);
			}
		}
Пример #15
0
		private void OnCompileInfoDialogExit(InfoDialog dialog)
		{
			compileDialog.SetFocus (Parent, OnStartProgramCompileExit);
		}
Пример #16
0
 static void RunAndWaitForProgram(string programName, ExecutionMode mode)
 {
     switch (mode)
     {
         case ExecutionMode.Debug:
             programName = @"--debug --debugger-agent=transport=dt_socket,address=0.0.0.0:" + settings.DebugSettings.Port + ",server=y " + programName;
             System.Diagnostics.Process proc = new System.Diagnostics.Process ();
             Dialog dialog = null;
             Thread escapeThread = null;
             CancellationTokenSource cts = new CancellationTokenSource();
             CancellationToken token = cts.Token;
             string portString  = ("Port: " + settings.DebugSettings.Port).PadRight(6).PadRight(6);
             if (settings.DebugSettings.TerminateWithEscape) {
                 escapeThread = new System.Threading.Thread (delegate() {
                     while (!token.IsCancellationRequested) {
                         if (Buttons.Instance.GetKeypress (token) == Buttons.ButtonStates.Escape) {
                             proc.Kill ();
                             Console.WriteLine ("Killing process");
                             cts.Cancel();
                         }
                     }
                 });
                 escapeThread.Start();
                 dialog = new InfoDialog (portString + " Press escape to terminate", false, "Debug Mode");
             }
             else
             {
                 dialog = new InfoDialog (portString + " Waiting for connection.", false, "Debug Mode");
             }
             dialog.Show ();
             proc.EnableRaisingEvents = false;
             Console.WriteLine ("Starting process: {0} with arguments: {1}", "/usr/local/bin/mono", programName);
             proc.StartInfo.FileName = "/usr/local/bin/mono";
             proc.StartInfo.Arguments = programName;
             proc.Start ();
             proc.WaitForExit ();
             if (escapeThread != null && !token.IsCancellationRequested) {
                 cts.Cancel();
                 escapeThread.Join();
             }
             break;
         case ExecutionMode.Normal:
             ProcessHelper.RunAndWaitForProcess("/usr/local/bin/mono", programName);
             break;
         case ExecutionMode.AOT:
             ProcessHelper.RunAndWaitForProcess("/usr/local/bin/mono", "--full-aot " + programName);
             break;
     }
 }
Пример #17
0
        static bool ShowProgramOptions(string programFolder)
        {
            string fileName = "";
            try {
                fileName = Directory.EnumerateFiles (programFolder, "*.exe").First ();
            } catch {
                var info = new InfoDialog (programFolder + "is not executable", true, "Program");
                info.Show ();
                Directory.Delete (programFolder, true);
                updateProgramList = true;
                return true;
            }

            var dialog = new SelectDialog<string> (new string[] {
                "Run Program",
                "Debug Program",
                "Run In AOT",
                "AOT Compile",
                "Delete Program",
            }, "Options", true);
            dialog.Show ();
            if (!dialog.EscPressed) {
                Action programAction = null;
                switch (dialog.GetSelectionIndex ()) {
                case 0:
                    Lcd.Instance.Clear ();
                    Lcd.Instance.DrawBitmap (monoLogo, new Point ((int)(Lcd.Width - monoLogo.Width) / 2, 5));
                    Rectangle textRect = new Rectangle (new Point (0, Lcd.Height - (int)Font.SmallFont.maxHeight - 2), new Point (Lcd.Width, Lcd.Height - 2));
                    Lcd.Instance.WriteTextBox (Font.SmallFont, textRect, "Running...", true, Lcd.Alignment.Center);
                    Lcd.Instance.Update ();
                    programAction = () => RunAndWaitForProgram (fileName, ExecutionMode.Normal);
                    break;
                case 1:
                    programAction = () => RunAndWaitForProgram (fileName, ExecutionMode.Debug);
                    break;
                case 2:
                    if (!AOTHelper.IsFileCompiled (fileName)) {
                        if (AOTCompileAndShowDialog (programFolder)) {
                            programAction = () => RunAndWaitForProgram (fileName, ExecutionMode.AOT);
                        }
                    } else {
                        programAction = () => RunAndWaitForProgram (fileName, ExecutionMode.AOT);
                    }
                    break;
                case 3:

                    if (AOTHelper.IsFileCompiled (fileName)) {
                        var questionDialog = new QuestionDialog ("Progran already compiled. Recompile?", "AOT recompile");
                        if (questionDialog.Show ()) {
                            AOTCompileAndShowDialog (programFolder);
                        }
                    } else {
                        AOTCompileAndShowDialog (programFolder);
                    }
                    break;
                case 4:
                    var question = new QuestionDialog ("Are you sure?", "Delete");
                    if (question.Show ()) {
                        var step = new StepContainer (() => {
                            Directory.Delete (programFolder, true);
                            return true;
                        }, "Deleting ", "Error deleting program");
                        var progressDialog = new ProgressDialog ("Program", step);
                        progressDialog.Show ();
                        updateProgramList = true;
                    }
                    break;
                }
                if (programAction != null)
                {
                    Console.WriteLine("Starting application");
                    programAction();
                    Console.WriteLine ("Done running application");
                }
                return updateProgramList;
            }
            return false;
        }
Пример #18
0
 static bool ShowUpdatesDialogs()
 {
     if (WiFiDevice.IsLinkUp()) {
         var step = new StepContainer(
             delegate()
             {
                 try{
                     return UpdateAvailable ();
                 }
                 catch
                 {
                     return false;
                 }
             },
             "Checking server", "No software updates available", "Software update available. Visit monobrick.dk");
         var dialog = new ProgressDialog("Updates", step);
         dialog.Show();
     }
     else
     {
         var dialog = new InfoDialog ("WiFi device is not pressent", true);
         dialog.Show();
     }
     return false;
 }
Пример #19
0
		public static void Main (string[] args)
		{
			if (!File.Exists (SuspendFile))
			{
				File.Create (SuspendFile);
			}
			FileSystemWatcher watcher = new FileSystemWatcher();
			watcher.Path = Path.GetDirectoryName(SuspendFile);
			watcher.NotifyFilter = NotifyFilters.LastWrite;
			watcher.Filter = Path.GetFileName(SuspendFile);
			watcher.Changed += OnSuspendFileChanged;
			watcher.EnableRaisingEvents = true;

			Menu menu = new Menu ("Main Menu");

			menu.AddItem(new ItemWithProgramList ("Programs", false));
			menu.AddItem(new ItemWiFiOptions ());
			menu.AddItem(new ItemWithSettings ());
			menu.AddItem(new ItemWithUpdateDialog ());
			//menu.AddItem(new ItemWithWebserver ());
			menu.AddItem(new ItemWithBrickInfo ());
			menu.AddItem(new ItemWithTurnOff ());

			container = new FirmwareMenuContainer (menu);

			Bitmap monoLogo = Bitmap.FromResouce(Assembly.GetExecutingAssembly(), "monologo.bitmap");
			Lcd.DrawBitmap (monoLogo, new Point ((int)(Lcd.Width - monoLogo.Width) / 2, 5));					
			Rectangle textRect = new Rectangle (new Point (0, Lcd.Height - (int)Font.SmallFont.maxHeight - 2), new Point (Lcd.Width, Lcd.Height - 2));

			Lcd.WriteTextBox (Font.SmallFont, textRect, "Initializing...", true, Lcd.Alignment.Center);
			Lcd.Update ();
			WiFiDevice.TurnOff ();
			ProgramManager.CreateSDCardFolder();
			Lcd.WriteTextBox (Font.SmallFont, textRect, "Loading settings...", true, Lcd.Alignment.Center);
			Lcd.Update ();
			FirmwareSettings.Load ();
			Lcd.WriteTextBox (Font.SmallFont, textRect, "Applying settings...", true, Lcd.Alignment.Center);
			Lcd.Update ();						
			if (FirmwareSettings.GeneralSettings.ConnectToWiFiAtStartUp) 
			{
				Lcd.WriteTextBox (Font.SmallFont, textRect, "Connecting to WiFi...", true, Lcd.Alignment.Center);
				Lcd.Update ();						
				if (WiFiDevice.TurnOn (FirmwareSettings.WiFiSettings.SSID, FirmwareSettings.WiFiSettings.Password, FirmwareSettings.WiFiSettings.Encryption, 40000)) 
				{
					if (FirmwareSettings.GeneralSettings.CheckForSwUpdatesAtStartUp)
					{
						container.Show (3); //show the menu container with the update dialog
						return;
					} 
					else 
					{
						var dialog = new InfoDialog ("Connected Successfully " + WiFiDevice.GetIpAddress ());
						dialog.Show ();
					} 
				} 
				else 
				{
					var dialog = new InfoDialog ("Failed to connect to WiFI Network");
					dialog.Show ();
				}
			}
			container.Show ();	
		}
Пример #20
0
        public static void Main(string[] args)
        {
            Lcd.Instance.DrawBitmap (monoLogo, new Point ((int)(Lcd.Width - monoLogo.Width) / 2, 5));
            Rectangle textRect = new Rectangle (new Point (0, Lcd.Height - (int)Font.SmallFont.maxHeight - 2), new Point (Lcd.Width, Lcd.Height - 2));

            Lcd.Instance.WriteTextBox (Font.SmallFont, textRect, "Initializing...", true, Lcd.Alignment.Center);
            Lcd.Instance.Update ();
            WiFiDevice.TurnOff ();
            if (!Directory.Exists (ProgramPathSdCard))
                Directory.CreateDirectory (ProgramPathSdCard);

            // JIT work-around remove when JIT problem is fixed
            System.Threading.Thread.Sleep (10);
            Console.WriteLine ("JIT workaround - please remove!!!");
            Lcd.Instance.WriteTextBox (Font.SmallFont, textRect, "Checking WiFi...", true, Lcd.Alignment.Center);
            Lcd.Instance.Update ();
            //WiFiDevice.IsLinkUp ();
            Lcd.Instance.WriteTextBox (Font.SmallFont, textRect, "Starting Mono Runtime...", true, Lcd.Alignment.Center);
            Lcd.Instance.Update ();
            string monoVersion = "Unknown";
            Type type = Type.GetType ("Mono.Runtime");
            if (type != null) {
                MethodInfo displayName = type.GetMethod ("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
                if (displayName != null)
                    monoVersion = (string)displayName.Invoke (null, null);
                Console.WriteLine ("Mono Version" + monoVersion);
            }
            string monoCLR = System.Reflection.Assembly.GetExecutingAssembly ().ImageRuntimeVersion;
            // JIT work-around end but look for more below

            //Load settings
            Lcd.Instance.WriteTextBox (Font.SmallFont, textRect, "Loading settings...", true, Lcd.Alignment.Center);
            Lcd.Instance.Update ();
            settings = settings.Load();
            if (settings != null) {
                Lcd.Instance.WriteTextBox (Font.SmallFont, textRect, "Applying settings...", true, Lcd.Alignment.Center);
                Lcd.Instance.Update ();
                settings.Save();// JIT work-around
              			WriteWpaSupplicantConfiguration(settings.WiFiSettings.SSID, settings.WiFiSettings.Password, settings.WiFiSettings.Encryption);
                if (settings.WiFiSettings.ConnectAtStartUp) {
                    Lcd.Instance.WriteTextBox (Font.SmallFont, textRect, "Connecting to WiFi...", true, Lcd.Alignment.Center);
                    Lcd.Instance.Update ();
                    if (WiFiDevice.TurnOn (60000)) {
                        WiFiDevice.GetIpAddress ();// JIT work-around
              				if (settings.GeneralSettings.CheckForSwUpdatesAtStartUp)
              				{
                            ShowUpdatesDialogs ();
                        }
                        else
                        {
                            var dialog = new InfoDialog ("Connected Successfully " + WiFiDevice.GetIpAddress (), true);
                            dialog.Show ();
                        }
                    }
                    else
                    {
                        var dialog = new InfoDialog ("Failed to connect to WiFI Network", true);
                        dialog.Show ();
                    }
                }
            }
            else
            {
                var dialog = new InfoDialog ("Failed to load settings", true);
                dialog.Show ();
              			settings = new FirmwareSettings();
            }

            //Keep showing the menu even if user press esc
            while(true)
            {
                ShowMainMenu();
            }
        }
Пример #21
0
 static bool ShowWiFiMenu()
 {
     List<IMenuItem> items = new List<IMenuItem> ();
     var ssidItem = new MenuItemWithCharacterInput("SSID", "Enter SSID", settings.WiFiSettings.SSID);
     ssidItem.OnDialogExit += delegate(string text) {
         new Thread(delegate() {
             settings.WiFiSettings.SSID = text;
             settings.Save();
         }).Start();
     };
     var passwordItem = new MenuItemWithCharacterInput("Password", "Password", settings.WiFiSettings.Password, true);
     passwordItem.OnDialogExit += delegate(string text) {
         new Thread(delegate() {
             settings.WiFiSettings.Password = text;
             settings.Save();
         }).Start();
     };
     var encryptionItem = new MenuItemWithOptions<string>("Encryption", new string[]{"None","WPA/2"}, settings.WiFiSettings.Encryption ? 1 : 0);
     encryptionItem.OnOptionChanged += delegate(string newOpstion) {
         new Thread(delegate() {
             if(newOpstion == "None")
                 settings.WiFiSettings.Encryption = false;
             else
                 settings.WiFiSettings.Encryption = true;
             settings.Save();
         }).Start();
     };
     var connectItem = new MenuItemWithCheckBox("Connect", WiFiDevice.IsLinkUp(),
         delegate(bool WiFiOn)
      		{
             bool isOn = WiFiOn;
             var createFileStep = new StepContainer(
                 delegate()
                 {
                     WriteWpaSupplicantConfiguration(settings.WiFiSettings.SSID,settings.WiFiSettings.Password,settings.WiFiSettings.Encryption);
                     return true;
                 },
                 "Creating file", "Error creating WPA file");
             var progressDialog = new ProgressDialog("WiFi", createFileStep);
             progressDialog.Show();
             if(WiFiOn){
                 var turnOffStep = new StepContainer(
                 delegate()
                 {
                     WiFiDevice.TurnOff();
                     return true;
                 },
                 "Turning Off","Error turning off WiFi","WiFi Disabled");
                 var dialog = new ProgressDialog("WiFi", turnOffStep);
                 dialog.Show();
                 isOn = false;
             }
             else{
                 var turnOnStep = new StepContainer(
                 delegate()
                 {
                     return WiFiDevice.TurnOn(60000);
                 },
                 "Connecting", "Failed to connect");
                 Dialog dialog = new ProgressDialog("WiFi", turnOnStep);
                 if(dialog.Show()){
                     if(settings.WiFiSettings.ConnectAtStartUp == false){
                         var question = new QuestionDialog("Do you want to connect at start-up?", "Settings");
                         if(question.Show()){
                             new Thread(delegate() {
                                 settings.WiFiSettings.ConnectAtStartUp = true;
                                 settings.Save();
                             }).Start();
                         }
                     }
                     dialog = new InfoDialog("Connected Successfully " + WiFiDevice.GetIpAddress(), true, "WiFi");
                     dialog.Show();
                     isOn = true;
                 }
                 else{
                     isOn = false;
                 }
             }
             return isOn;
      		}
     );
     items.Add(ssidItem);
     items.Add(passwordItem);
     items.Add(encryptionItem);
     items.Add(connectItem);
     //Show the menu
     Menu m = new Menu ("WiFi Connection", items);
     m.Show ();
     return false;
 }