Статьи

IoT с Windows на устройствах

Автор Майкл Крамп

Интернет вещей (IoT) позволяет нам связывать людей и вещи по всему миру, используя адрес IPV6. С размером IPV6 мы могли бы назначить IP-адрес каждому атому на поверхности Земли, и у нас осталось бы достаточно IP-адресов, чтобы сделать еще 100+ земель. Другими словами, люди могут легко назначить IP-адрес каждой «вещи» на планете. Не удивительно, что мы начали видеть их включенными в такие вещи, как имплантаты для контроля сердца, умные термостаты и устройства для открывания гаражных ворот, которые используют WiFi для удаленного мониторинга.

Где вписывается Microsoft? На // Build 2014 они продемонстрировали версию Windows, работающую на плате Intel Galileo. Они открыли   страницу регистрации, и мы пошли. Начиная с // Build 2014, было выпущено лучшее оборудование, а также обновлены образы Windows для встраиваемых устройств. Мы также недавно слышали о  Windows 10, работающей на Raspberry Pi 2 ! У нас впереди захватывающие времена!

В этой статье я расскажу вам о том, что вам нужно для того, чтобы начать разработку приложений, работающих под управлением Microsoft Windows на устройствах с использованием платы Intel Galileo V2. Поскольку мы будем использовать Visual Studio 2013, я покажу вам, как вы можете использовать платформу Windows и использовать знакомые программы для Win32.

Плата Intel Galileo V2

Вы можете купить доску в нескольких электронных магазинах. Просто выберите свой любимый и убедитесь, что это модель V2. Открыв коробку, вы увидите свою плату в антистатической сумке и широкий ассортимент адаптеров для различных розеток, найденных по всему миру. Это также идет с некоторой краткой информацией о безопасности.

Intel Galileo V2

Intel Galileo V2

Сама плата выглядит следующим образом:

Intel Galileo V2

  1. Подключается к внешнему источнику питания.
  2. Порт Ethernet
  3. Подключается к ПК через USB
  4. Дополнительный порт USB
  5. Слот для карт памяти microSD (технические характеристики рекомендуют не менее 16 ГБ)

Теперь, когда вы знаете основы своего оборудования, мы углубимся в изучение и рассмотрим его настройку для загрузки Windows.

Настройка вашей платы Intel Galileo V2

Плата Intel Galileo V2 указывает на  следующие инструкции . Я обнаружил, что единственными шагами, которые были особенно важны, было то, что вы обновили драйверы программного обеспечения и смогли запустить тест моргания на фактической плате (не на внешнем светодиоде). Если вы можете сделать обе эти вещи, перейдите к следующим шагам:

  • Вставьте карту microSD в компьютер и отформатируйте ее с помощью Fat32.
  • Загрузите следующие три файла с сайта MS Connect (вам необходимо  зарегистрироваться  и войти в систему, чтобы загрузить эти файлы):

    1. apply-BootMedia.cmd  — сценарий обработки изображений для образа Windows
    2. Изображения Microsoft Windows (WIM) для встроенных устройств
    3. MSI Installer  (необязательно, но рекомендуется) устанавливает шаблоны и приложения, которые помогают выполнять определенные задачи с вашим Galileo.
  • Перейдите в каталог, в который вы загрузили файлы, и выполните следующую команду в командной строке администратора.
apply-bootmedia.cmd -destination {WhateverYourSDCardDriveLetterIS} -image {latest WIM image} -hostname mygalileo -password admin

Вы должны увидеть следующее на экране, когда все будет готово. (обратите внимание, что моя буква диска была E 🙂 Обратите  особое внимание  на имя хоста / имя пользователя и пароль, так как это понадобится вам позже. Просто извлеките microSD из вашего ПК и вставьте microSD в вашу плату вместе с кабелем Ethernet и кабелем питания.

createbootsd

После завершения этого процесса вы готовы запустить Windows для встроенных устройств на вашей плате Intel Galileo.

Убедитесь, что на вашем компьютере установлен Telnet. В Интернете есть различные  руководства о том, как это сделать и выключить вашу плату Intel Galileo.

Если вы еще этого не сделали, сейчас самое время запустить  программу MSI Installer,  которая создает шаблоны Visual Studio, а также устанавливает приложение под названием Galileo Watcher.

При запуске приложения вы должны увидеть следующее:

galwatcher

Если вы щелкните правой кнопкой мыши и выберите «Telnet here», вы можете войти в систему, используя имя пользователя и пароль, которые вы создали ранее. Вы должны попасть в каталог C: \ windows \ system32:

User name: Administrator
Password:

Microsoft Windows [Version 6.3.9600]
Copyright (c) Microsoft Corporation. All rights reserved.

C:\windows\system32>

Очевидно, что вы можете перейти на диск C: \ и просмотреть файлы, хранящиеся на вашей плате Intel Galileo, как показано ниже.

каталог

Просто щелкнув правой кнопкой мыши на своей плате Galileo (используя Galileo Watcher), вы также можете открыть веб-браузер, который позволяет просматривать следующее:

  • Список заданий
  • Список файлов
  • Статистика памяти

Вот пример того, что вы можете найти на http: // yourgalileoipaddress / memstat

36 percent of memory is in use.
There are     239 total Mbytes of physical memory.
There are     152 free  Mbytes of physical memory.
There are    1263 total Mbytes of paging file.
There are    1179 free  Mbytes of paging file.
There are    2047 total Mbytes of virtual memory.
There are    2042 free  Mbytes of virtual memory.
There are       0 free  Mbytes of extended memory.

Изучение шаблона Visual Studio

Included in the MSI that contains the Galileo Watcher program is a Visual C++ template that allows you to write an app using Visual Studio. It is basically a C++ console app that has references to the Galileo-SDK, so that we can talk to the Arduino side of things. The template looks like the following :

If you navigate to the Main.cpp in the “Source Files” folder, you should see the following code:

// Main.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "arduino.h"

int _tmain(int argc, _TCHAR* argv[])
{
    return RunArduinoSketch();
}

int led = 13;  // This is the pin the LED is attached to.

void setup()
{
    // TODO: Add your code here

    pinMode(led, OUTPUT);       // Configure the pin for OUTPUT so you can turn on the LED.
}

// the loop routine runs over and over again forever:
void loop()
{
    // TODO: Add your code here

    digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
    Log(L"LED OFF\n");
    delay(1000);               // wait for a second
    digitalWrite(led, HIGH);   // turn the LED on by making the voltage HIGH
    Log(L"LED ON\n");
    delay(1000);               // wait for a second
}

The main thing to take away from this is that it includes the arduino libraries and upon launch calls the RunArduinoSketch method. It sets up an led variable that is attached to a pin on the board. This pin will simply blink on and off via the loop method.

You can hit F12 which is “Go To Definition” on theRunArduinoSketch() and notice that it opens arduino.h and calls the setup method.

You will find this code Identical to the Arduino IDE sample code with the exception of pulling in the Arduino header file and the Log method as shown below:

мигания

Make sure you have a LED pin in Pin 13 (The longer Pin connects to Pin 13 and the shorter one to Ground). If you do not have a kit such as thefollowing one – which contains some LEDs that are required, then you can also comment out the LED code to view the log messages to ensure your board and Visual Studio are talking to each other.

Run It!

As long as you left the default name of your board as mygalileo, you can simply press “Remote Windows Debugger”. It will pop up a message asking for authentication and you should use the following if you haven’t changed it.

аутентификация

The password is a lowercase “admin” (without quotes).

Your device should have a blinking LED as shown below:

If you take a look in your Output Window in Visual Studio, you will see the following:

LED ON
LED OFF
LED ON
LED OFF
LED ON
LED OFF
LED ON

This is coming from the code shown earlier.

Writing an App in Visual C#

If you create a new Visual C# console application and change the build options to x86, then you can use certain parts of .NET to write an app for the board. Here is a small app that I wrote that using theSystem.Threading and System.Globalization namespaces and it runs just fine on my Galileo V2 board :

static void Main(string[] args)
{
    Console.WriteLine("Telerik Developer Network");
    CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
    Console.WriteLine("The Current Culture is : " + currentCulture);
}

If I copy the executable onto my microSD card (just create a network share), and run it, then it displays the following :

C:\test>HelloWorld
Telerik Developer Network
The Current Culture is : en-US

I’ve read about others having success playing with other namespaces, but until we see what Microsoft’s plans are for 2015, it looks like this will be a process of trial and error.

It is advisable to shutdown Windows before closing the command prompt as their is no UI yet for Windows on Devices. You can do so by:

shutdown /s /t 0

What’s Next?

I think we will learn more at the Build 2015 conference about Microsoft’s plans for Windows on Devices. As stated earlier in this article, Microsoft has announced they will be bringing Windows 10 to Raspberry Pi 2! These devices run about $35 USD and pack a powerful punch in terms of hardware. Exciting times are upon us!

Also, since your probably are a .NET developer and currently developing a solution of some sort. I’d encourage you to to download and explore ourASP.NETWPF and Windows Universal apps UI suites, as well take a look at the overall collection.