[:en]One world — one frontend or first flight instrument built with HTML[:ru]Один мир — один фронтенд или первый авиационный прибор на HTML[:]
[:en]Good day colleagues! One more good day which will ends quickly become past and will present one more step forward for us. How will front end development we are all passionate of look like tomorrow?
[:ru]Доброго дня, коллеги! Еще одного доброго дня который быстро промелькнет, уйдет в прошлое и подарит миру еще один шаг вперед. Какой будет завтра фронтенд разработка к которой мы идем, делая посильный вклад в развитие открытой платформы?
[:][:en]
History likes unification
To predict the future lets look into the past… If we do this — we see that solid thread of unification goes through mankind`s history.
Unification — effective method to decrease diversity. Unification is a kind of systematisation. Aim for unification is to place elements in particular order building strict system which is comfortable to use. (c) Wikipedia
Unification have been succeed in science, engineering, politics and business.
Europe in 18 century:
Europe nowadays:
Unification never stops:
- All airplanes look similar nowadays and it is hard to differ Boeing from Airbus, but it was not like this in the beginning! Just have a look, some of them look as weird as GWT or Adobe Flex
- 200 years ago there were dozen of countries in Europe. Today we see European Union absence of borders and integration still crawls further;
- Do you enjoy unified lamp sockets? There were much more kinds of them. But…
In every field of knowledge there is a limit after hitting which diversity decreases and only best solutions survive. This works for software development as well.
We develop software for 60 years and such a common problem as interface description is not standardised yet. However in recent years one technology is gonna to go out from labyrinth of experiments. This technology is compatible with widest range of devices and is being used by milliards of people every day. This is HTML/CSS. And if you say that HTML is only a markup language, I would argue:»It is not. Seems that you missed some news.»
HTML today and tomorrow
HTML/JS today is the most popular platform for UI development of any complexity and it still goes up. Firefox OS, Tizen, Smart TV, Chrome OS, Windows 8 — it is short list of operating systems which use HTML as application development platform. Variety of devices which use HTML growth as well as it`s popularity and it is quite easy to understand why. Usage of HTML/JS shortens development cycle and decreases amount of code to test. Browser takes care of many duties which lower level languages delegate to developer. And what do speed of development and reliability mean nowadays? What are benefits of using single front end platform? Is it just a competitive advantage and speed of innovations? A lot of people nowadays think that it is even more.
HTML/JS is good enough to expand it`s limits further. It is quick, flexible and clear approach to create visual components, UIs of any kind.
Below you can find details of HTML5 usage in aircraft manufacturing industry. We will consider possible approaches to develop electronic flight instrumentation systems («EFIS») with help of HTML/JavaScript. Also will use HTML/JS to implement artificial horizon. What is good — it will work even if you do not have own plane yet =)
Justification
HTML driven EFIS systems are easier to share via computer network. This is highly valuable in the age of remotely controlled drones.
Usage of unified, popular and reliable technology decreases development cost with standardization of development flow and technologies stack.
Moving responsibility for rendering from indicator developer to browser core is able to shorten development cycle and reduce amount of code to test. This opportunity is highly valued in aviation world where development cycle lasts for years.
Flight and marine indicators are not just new career opportunities for front-end developers. They could establish new kind of UI components market and be basis for new qualitative leap for aircraft and shipbuilding industries.
UI architecture proposal
Modern instrumental panels consist of LCD panels showing different flight instruments.
HTML allows manufacturer to configure any layouts for displays.
One of display layouts possible
Instruments should be implemented as JS classes. Constructor of such a class expects CSS selector as first argument so instruments can be deployed to layout cell as following
new AttitudeIndicator('#leftColumn1')
We see that instrument is being used as black box without any knowledge about it`s internals. This makes possible existence of dynamic and competitive market of flight, marine etc. instruments built with HTML/CSS/JS.
Indicators development industry is quite conservative. List of UI solutions being used is limited and boring. Main reason for this is highest standards for reliability. Due to amount of testing CSS is able to break this limit. Being used on milliard of devices daily CSS is robust and powerful enough to be a fresh breath for industry.
Recent layout have navigation map as central element. Lets suppose that weather became worse and now meteo information is top priority for pilot. CSS/JS allows to implement brand new level of UX for flight instruments with just a few lines of code. Click on weather radar (top-right) in order to move it to central panel.
Interactive demo for swapping instruments
Sensors data
It is assumed that displays browsers are connected to shared data bus.
Data flow scheme
Developer can get altitude data in JavaScript code as following
var altitude = window.flightData.altitudeSensor.altitude;
and getting current coordinates look like
var longtitude = window.flightData.gpsSensor.longtitude; var latitude = window.flightData.gpsSensor.latitude;
Similar approach is being successfully used to access native resources in PhoneGap and Adobe Air.
Attitude indicator
Instrument consists just of few moving parts and key frame animations are absent. All we need is smooth indication of two values: roll and pitch of aircraft. So using few absolute positioned layers and CSS transitions would be most performant and compatible solution for such a task.
Implemented as JavaScript class AttitudeIndicator(cssSelector, autoUpdate).
Arguments of constructor:
- cssSelector specifies element for indicator deployment;
- autoUpdate optional boolean argument defines will indicator use HTML5 Orientation API or not& If it is true — Orientation API is enabled, otherwise value have to be sent with help of updateAngles(horizontalAngleDegrees, verticalAngleDegrees) method.
During initialization and operation indicator uses as more as possible of native functions and as less as possible of calls to DOM. Elements are created with help of documentFragment to minimize UI locks.
p.initElements = function() {
var docFragment = document.createDocumentFragment();
this.wrapperNode = document.createElement('div');
//Creating all nodes and adding them to wrapperNode ...
this.planeMarkNode.appendChild(this.planeMarkImage);
docFragment.appendChild(this.wrapperNode);
this.node.appendChild(docFragment);
Animation is based on CSS3 transitions with periodic values updating.
If indicator was created with autoUpdate equals to true — values are updated on deviceOrientation event.
updateAngles(horizontalAngleDegrees, verticalAngleDegrees) {
this.verticalMeasurementline.style[this.transformString] = 'translate(0, ' + verticalTransform + 'px)';
//Others elements are being turned ...
}
In case if autoUpdate was set to false — deviceOrientation listener will not be added.
It is fun to know that deviceOrientation axis for Maс and iOS are swapped. For Mac it detects orientation of keyboard part and for iPad it works for screen ofcourse. So this have to be fixed by userAgent based condition.
Video of first flight ever using HTML/JS aircraft indicator
Try artificial horizon
Orientation API support was tested on Mac Book Pro (without SSD) and iPad
Source code
Conclusion
HTML/JS is adult enough to be used for production of vehicle indicators. Platform is tested by millions of users daily and is amazingly robust. Features of HTML/CSS/JS stack allow rapid development of quite complex and dynamic indicators which are easily accessible via network which is highly valuable for any kind of drones. Web — driven indicators are not just a new job opportunity for front end developers, it is ready to use approach to have faster software evolution for product owners and create new kind of competitive market which can be basis for new era in indicators development industry.
P.S.
IT industry loses tons of energy porting UI from one language to another. Windows, Mac OS, Unix, Android, iOS, Windows Mobile, Blackberry, Tizen, FirefoxOS, embedded deveices. Mankind need one front-end to be better. So let`s take a sober look at the future, move away from weird, experimental solutions to well known, open and unified technologies. And… have a good day![:ru]
Для того что бы понять будущее давайте обратимся к прошлому… Изучая и анализируя пройденный человечеством путь мы увидим как крепнущая нить унификации проходит через всю историю.
Унификация — распространённый и эффективный метод устранения излишнего многообразия, является разновидностью систематизации и преследует цель распределения предметов в чёткую систему, удобную для пользования. (c) Wikipedia
Унификация добилась весьма серьезных успехов в политике, авиа и автостроении, инженерных решениях и электронике.
Европа в 18 веке:
Европа сейчас:
Факты:
- Все современные пассажирские самолеты похожи. Тяжело отличить Boeing от Airbus, но изначально разнообразие форм было потрясяющим. Просто взгляните на эти недоразумения, некоторые похожи на Adobe Flex и GWT =)
- Еще 200 лет назад в Европе существовало более 50 отдельных княжеств и государств. Сегодня? — Евросоюз, минимум границ, интеграция;
- Вам нравятся унифицированные патроны для электрических лампочек? Правда удобно? Сначала их было куда больше, но…
В тот момент, когда человечество накапливает достаточное количество знаний в определенной области — замедляется поиск возможных решений и вместе с этим сокращается типовое разнообразие. Остаются самые популярные, эффективные и стойкие решения. Этот барьер, этап актуален для любой области — будь то политика, транспорт или инженерное дело. Актуально это и для программирования.
Унификация и UI
Мы разрабатываем ПО уже 60 лет при этом такая типовая задача как описание интерфейса все еще не имеет единого решения, хотя в последнее время стало заметным решение претендующее на роль долгожданного стандарта. Эту технологию используют миллионы людей ежедневно — это HTML.
И если вы скажете:»HTML это всего лишь язык описания веб страниц!», — я с уверенностью отвечу, что это уже давно не так, что вы многое пропустили.
HTML сегодня — самая популярная платформа для создания UI и он продолжает набирать обороты. Firefox OS, Tizen, Smart TV, Chrome OS, Windows 8 — вот краткий список операционных систем которые поддерживают HTML/JS, как основную платформу разработки приложений. Количество устройств использующих открытый фронтенд растет и это понятно — его применение уменьшает объем кода нуждающегося в тестировании, ускоряет разработку по сравнению с низкоуровневыми языками. Скорость и надежность дают ощутимые преимущества в конкурентной борьбе и становятся все более важны с каждым днем. Эти приемущества делают HTML/JS достойными дальнейшего расширения сферы применения.
Ниже — попытка сдвинуть наше представление о HTML/JS, применив их в самолетостроении. Речь пойдет об общих принципах использования платформы в приборных панелях самолетов (electronic flight instrumentation systems — «EFIS») и о разработке первого авиационного прибора на HTML — искуственного горизонта.
Обоснование
Приборы разработанные на базе web — технологий обладают высокой доступностью через компьютерный сети. Это особенно важно в век беспилотных летательных аппаратов.
Применение единой, популярной технологии для отображения приборов позволит уменьшить затраты на разработку интерфейсов за счет стандартизации.
Перенос ответственности за рендеринг на ядро браузера снизит объем тестируемого кода приборной панели, ускорит процесс разработки.
Авиационные и судовые приборы — это не только новые карьерные возможности для front-end инженеров, но и новый тип рынка UI компонент, который может стать предпосылкой для качественного рывка в отрасли.
Предполагаемая архитектура UI
Современные приборные панели — это LCD дисплеи отображающие приборы с различной информацией о состоянии машины.
С помощью HTML разметки производитель может самостоятельно задать сетку расположения приборов на дисплее.
Один из возможных вариантов сеткиКаждый прибор оформляется в виде отдельного класса. В его конструктор передается селектор на предназначенную прибору ячейку. Например размещение искуственного горизонта в первую ячейку будет выглядеть как
new AttitudeIndicator('#leftColumn1')
Мы видим, что для использования приборов не требуется знаний о его внутреннем устройстве. Это открывает возможности для создания живого и конкурентного рынка авиационных, морских и пр. приборов разработанных на HTML/CSS/JS.
Индустрия разработки индикаторов весьма консервативна, список используемых UI решений скуден и скушен. Главная причина этого — повышенные требования к надежности. Благодаря объему тестирования CSS может обойти это ограничение. Используемый на миллиардах устройств ежедневно CSS — достаточно надежная и мощная технология что бы стать глотком свежего воздуха для индустрии.
В предыдущей сетке центральным элементом была навигационная карта. Предположим, что погодные условия ухудшилась и теперь информация погодного радара стала приоритетной для пилота. CSS/JS позволяют создать совершенно новый уровень UX для отрасли в нескольких строках кода. Щелкните по погодному радару (правый верхний угол) для переноса его в центральную ячейку.
Интерактивная демонстрация переключения основного прибора
Данные приборов
Предполагается, что браузеры дисплеев будут подключены к общей шине данных.
Схема передачи данных
Для разработчика это значит, что получить данные о текущей высоте можно через
var altitude = window.flightData.altitudeSensor.altitude;
Аналог для широты и долготы
var longtitude = window.flightData.gpsSensor.longtitude; var latitude = window.flightData.gpsSensor.latitude;
Подобный подход уже сейчас используется в PhoneGap и AdobeAir для доступа к нативным ресурсам.
Разработка искуственного горизонта
Авиагоризонт состоит из небольшого количества подвижных элементов, а покадровые анимации отсутствуют. Все что необходимо — плавное отображение двух величин: крена вертикального крена. Нам будет достаточно нескольких слоев с абсолютным позиционированием и css transitions. Transitions — нативная имплементация твинов в браузере и похоже такое решение будет самым быстрым и совместимым из html/css стека.
Реализация
Прибор представлен в виде JS класса AttitudeIndicator(cssSelector, autoUpdate)
Входящие аргуметы конструктора:
- cssSelector элемента для развертывания индикатора;
- autoUpdate необязательный boolean параметр определяющий будет ли прибор использовать HTML5 API для получение координат. Если true — используется HTML5 Orientation API, если false — параметры передаются извне с помощью метода updateAngles(horizontalAngleDegrees, verticalAngleDegrees)
При инициализации и работе используется максимум нативных функций рендеринга и минимум вызовов.
Основные элементы добавляются к DOM единожды через documentFragment что бы блокировать работу браузера минимально.
p.initElements = function() {
var docFragment = document.createDocumentFragment();
this.wrapperNode = document.createElement('div');
//создание всех узлов и добавление к wrapperNode
this.planeMarkNode.appendChild(this.planeMarkImage);
docFragment.appendChild(this.wrapperNode);
this.node.appendChild(docFragment);
Анимация происходит через CSS3 transition движущихся элементов при периодической передаче данных. Из события deviceOrientation происходит вызов функции:
updateAngles(horizontalAngleDegrees, verticalAngleDegrees) {
this.verticalMeasurementline.style[this.transformString] = 'translate(0, ' + verticalTransform + 'px)';
//Поворот остальных элементов ...
}
Соответственно если обьект создан с autoUpdate = true (второй аргумент конструктора) слушатель на deviceOrientation не устанавливается.
Занимательно что deviceOrientation на Mac дает значения осей для корпуса, а не монитора. Соответственно между iPad и Mac есть разница в осях. Исправляется условием по userAgent, но вероятно есть библиотеки с расширенной поддержкой устройств? Можете что то посоветовать?
Попробуйте авиагоризонт в действии
Проверено на данных встроенных гироскопов Mac Book (без SSD) и iPad .
Исходный код
Видео первого в истории полета с использованием HTML/JS авиационного прибора:
Заключение
HTML/CSS/JS -достаточно зрелый стек для создания авиационных и корабельных приборов. Он обладает рядом преимуществ по части скорости, гибкости разработки, а созданные таким образом приборы надежны и обладают чрезвычайно высокой сетевой доступностью, что особо важно в век беспилотных ЛА.
Еще одна возможность скрывающаяся в применении веб — технологий для разработки приборов — создание конкурентного рынка, создающего небывалый выбор производителям ЛА и предпосылки для качественного скачка в индустрии авиационных и корабельных приборов.
P.S.
Вне всякого сомнения — сейчас на портировании интерфейса между платформами человечество теряет гигантское количество энергии. Windows, OSx, iOS, Blackberry, Android… А вы видели язык разметки в Android? Разве это не странно — дублировать существующие и успешные парадигмы?
Давайте же мыслить трезво, держа уверенный шаг на пути в лучшее будущее и… Доброго дня![:]
Weed effect passed so I can see why? cos of difference if how NVidia and ATI and…rendered UI and cos of difference how Win,Mac,(btw I couldn’t run this on Win >:))) …cos of difference of browsers, and new and old versions…cos of difference of devices (did u said works on IPad, my laptop doesn’t have gyro yet?) and difference of UI towards devices (you flight with touch or mouse I prefer joystick …) ……
This is not an article about cross browser compatibility. If somebody will build airplane indicator with JS/HTML he will use custom WebKit or FF fork + Linux. So no need to support Win7 + IE9 😉
navigator.userAgent.match(/(iPad|iPhone|iPod)/g) why not /iPw+/g ?
I was quite careful with user agents matches. There is bunch of them http://www.useragentstring.com/pages/All/
This will work fine, thanks.
maaaan, dont trust web-browsers as avionics, this is a critical operation, where your life depends on that equipament. i just imagine flight with my avionics with huge latency.
Ok, understand you =) Actually the idea is that you get data in C, operate data in C, but display data with HTML/JS since it is quite performant and stable rendering platform which is used very very widely.
I`d say we are not Web developers anymore, at least a lot of us. Front-end or UI developer fits better today. Web was the origin, but now it is only one of environments possible.
We`ve been flying with this thing for 20 minutes, it was not that bad. Since instrument is simple it was quite easy to implement avoiding memory leaks and performance degradation. The biggest issue was mac`s gyro sensitivity, should use more specialized sensor for sure.,,