Статьи

Создание собственного языка Cross Mobile Platform с помощью Xtext

В этом году EclipseCon, фонд, успешно провел e4 Mars Rover Challenge с НАСА. Одна команда написала приложение для iPhone, чтобы управлять ровером. Как большой поклонник инноваций в мобильных приложениях, это сразу привлекло мое внимание, поэтому я связался со всей командой. Питер и Хейко используют Xtext для предоставления собственного DSL для мобильной разработки. Этот подход был одной из главных тенденций в индустрии программного обеспечения за последний год и интересует всех, учитывая объявление Apple на прошлой неделе. 

Я говорил с Питером Фрейзом и Хейко Беренсом о том, как они использовали Xtext для обеспечения DSL для кроссплатформенной разработки для мобильных устройств. Некоторые части этого будут сделаны в будущем с открытым исходным кодом, поэтому, если вы заинтересованы в немного другом подходе к разработке мобильных приложений, читайте дальше.

Джеймс: Привет, Питер, Привет, Хейко, не могли бы вы представиться тем, кто может вас не знать?

Питер:  Мы оба — архитекторы программного обеспечения и консультанты, работающие с itemis . Itemis наиболее известен своей работой в области разработки программного обеспечения на основе моделей (MDSD) и языков, специфичных для предметной области (DSL). Itemis является участником стратегического развития Eclipse, финансируя работу восьми коммиттеров полного дня, большинство из которых работают над Xtext. Хейко и я также являемся частью этой команды.

Джеймс: Хайко, вы рассказали, как Xt ext может генерировать приложения для iPhone, как это работает?

Хейко:  В этом 12-минутном выступлении я использовал предметно-ориентированный язык, созданный с помощью Xtext,  и генератор кода, реализованный с помощью Xpand. создать полноценное приложение для iPhone во время презентации. Используя этот конкретный язык, я продемонстрировал некоторые функции IDE, такие как семантический анализ ошибок, завершение кода и интеграция Xcode. Каждый раз, когда я что-то менял на этом языке высокого уровня, он автоматически синхронизировал соответствующие файлы кода Objective-C. От редактора было достаточно одного клика, чтобы скомпилировать проект Xcode и показать симулятор iPhone, который наконец запустился и запустил приложение для iPhone в реальном времени. 

 

 

Джеймс: В каком формате пишутся приложения?

Хейко:  Язык, который я создал для этого выступления, концентрируется на мобильных приложениях, управляемых данными, которые извлекают данные из существующих веб-ресурсов, таких как блоги или REST-API. Это упрощает структуру приложения, навигацию между представлениями и даже абстрагирует такие вещи, как асинхронная выборка данных или кэширование.

tabbarApplication itemisApp {

button {
title= "Blog"
icon= "chat.png"
view= BlogList( Blogposts() )
}

button {
title= "Sessions"
icon= "microphone.png"
view= SessionList( AllSessionItems() )
}

button {
title= "Presenters"
icon= "person.png"
view= SpeakerList( AllSpeakerItems() )
}

}

// leaving out other views, entity description and content providers

tableview SpeakerList(Speaker[] speakers) {
title= "Presenters"
section {
cell Default foreach speakers as s {
text= s.name
image= s.photoUrl
action= SpeakerDetails(s)
}
}
}

detailsview SpeakerDetails(Speaker speaker) {
title= "Presenter"
header {
title= speaker.name
details= speaker.bio
image= speaker.photoUrl
}

section {
cell Default foreach split(speaker.sessionTitles, ", ") as title {
text= title
action= SessionDetails(SessionByTitle(title))
}
}

section {
cell Value2 {
text= "mail"
details= speaker.email
action= ("mailto:"speaker.email)
}

cell Value2 {
text= "blog"
details= speaker.blog
action= ("http://"speaker.blog)
}

}

}

Этот фрагмент отвечает за приложение, которое вы можете увидеть на скриншотах выше. Несмотря на то, что я пропустил некоторые аспекты, такие как извлечение данных (например, контент-провайдеры AllSessionItems ()
или
SessionByTitle (String) ), вы, безусловно, поняли идею.

Этот типобезопасный язык затем подается в генератор кода, который преобразует его в код Objective-C, связанный с API-интерфейсом iPhone, ориентированным на обратный вызов, и заботится об управлении памятью и обработке ошибок.

Джеймс: Будет ли это доступно для использования в Eclipse в ближайшее время?


Хайко:
На самом деле, мы думаем об открытии (по крайней мере, части) его с открытым исходным кодом. Как только он будет доступен, мы с Питером будем вести блог об этом и связанных материалах, которые в настоящее время находятся в стадии разработки.

Джеймс : Вы смотрите на создание других двоичных файлов с использованием этого подхода, таких как Android?

Питер: Да, мы делаем. Кроссплатформенная поддержка является одним из основных преимуществ разработки программного обеспечения на основе моделей: вы создаете модель один раз и генерируете большую часть кода для нескольких платформ. Так что, да, мы планируем поддерживать Android в качестве платформы. Если у вас есть шанс, приходите к нам на DroidCon в Берлине. Мы рады представить вам первую версию нашей поддержки Android.

By the way, we would’ve used a model-driven
approach anyway, as we see many other benefits, such as being able to
program on an appropriate level of abstraction.

James: You
said «programming» when you referred to using models — shouldn’t you
use the term «modeling»?

Peter: No, actually
not. As Heiko explained, domain specific languages look and feel much
like a programming language. Of course, we need to define the language
to make it fit our needs — this is one of the major advantages of DSLs:
you can define a language which really fits your needs. No cumbersome
syntax or superfluous concepts. Just leave out all the ballast and keep
what you really needs. We see ourselves more like language designers
than as modelers, really.

James: How do the new iPhone
development terms affect your approach? Are you concerned?

Heiko: As you can see from the
snippet above, the 
DSL is only used to specify the structure of your
app. The code generator picks snippets of plain Objective-C code we have
written before and combines them according to that specification. We do
not use any intermediate layer here — the generated Objective-C code
uses Apple’s official APIs. If you need any further application logic it
has then to be coded in plain Objective-C by hand. For developer’s
support, we apply well-known idioms such as the Generation Gap Pattern
and features of Objective-C such as categories to allow for an easy
integration of generated and manually implemented code parts. Thus, the
final application is originally written in Objective-C. We think this
pretty much is what the iPhone development terms ask for.

James: Can you give us some
background to the e4 Mars Rover challenge?

Peter: Sure! NASA
and the Eclipse e4 team had the idea to run an exciting contest at
EclipseCon to involve people with the upcoming e4 platform. Jeff Norris
and his team at NASA built a LEGO Mindstorms Mars Rover which is
controlled by a Java program on a computer nearby the Mars arena. This
computer acts as a relay for a web service running on Amazon EC2. Boris
Bokowski and his team built an e4 client which the player can use to
connect to the web service and send driving commands. When it’s the
players turn, those commands get send down to the local computer which
sends them to the Mars Rover. Overhead the arena, a USB camera is
monitoring the course of events, allowing the local computer to perform
some image recognition in order to derive the current location and
heading of the Mars Rover. Players need to register in order to play.
They can then use the e4 client to control the rover. The challenge is
to drive the Rover to certain locations in the arena, marked with
different colors and present one of the two tools mounted on the Rover
(drill or spectrometer). The quicker you present the right tool at the
right spot, the more points you get. Now, as this is to be a simulation
of the situation on Mars, feedback (in the form of the overhead camera
image) will be sent with a certain delay of about 2 seconds. Of course,
everybody circumvented this limitation by sitting down right next to the
area 🙂

The second part of the challenge was to come up with an
improved e4-based client. I’ve seen some really amazing clients, some of
which used image recognition to simulate semi-autonomous behaviour.
Truly amazing!

James: What made you think of using the
iPhone to control this?

Peter: The idea to use the
iPhone as a client came to my mind when I dropped off my computer in my
hotel room one evening. When I was in the escalator, I realized that I
wouldn’t be able to take part in the challenge that evening. But then I
realized that I’m carrying this little computer with me almost all of
the time: my iPhone. So I decided to develop an iPhone client for the
challenge. When I talked with Heiko about this, he was instantly excited
about this as well. So we decided to team up. Heiko programmed and
designed the front end, while I was responsible for the communication
with the back-end.

 
 

James: Are you using e4 at
all in this example?

 Heiko:
No, we don’t. This is a 100% native iPhone application written in
Objective-C. We used the e4 client solely to copy the communication
layer between client and server.

 

James: So
how does it all work in the background?

 Heiko: Well, when you start the app it
registers itself at the server to line up in the queue of players. Once
it’s your turn, the app vibrates to call your attention. During your
mission, we use the accelerometer to obtain x,y-coordinates we then
transform into proper wheel commands of the tank-like robot. All these
data is being sent via a simple REST API. The server eventually pushes
commands via bluetooth, verifies accomplished mission goals with RFID
sensors and records the robot with a camera. The server acts as a hub or
“Mars control center” every client connects to. Actually, there was
cloud-computing involved to handle data load, but this is independent
from the iPhone app and transparent to any other client, too.

 Feedback such as camera input
and current mission objectives are being fed back to the iPhone using
REST Services respectively. All this happens asynchronously such that
any involved component including the iPhone keeps responsive. If you
close the app it unregisters itself from the player’s queue — this
completes our idea of a «quick Mars rover gaming mission».

BTW, we created a mini-site
about this project at iPhoneMarsRover.com

 James: Could
you share some of the critical code snippets for the app with us?

Peter: The
app we built is a native iPhone application, written in Objective-C, so
we can use all of the features the iPhone platform provides, such as
the accelerometer. Communication with the web service has to be
performed using HTTP — the web service actually is RESTful. I started
out using blocking HTTP calls, which of course resulted in bad
responsiveness in the UI. Eventually, I switched to using ASIHTTP,
which provides a nice interface for REST services. Here is the code we
use to send our driving commands over to the web service

- (void) performCommand: (NSString*) command withUrl: (NSString*) urlString {
ASIHTTPRequest *request = [[ASIHTTPRequest requestWithURL: [NSURL URLWithString:urlString]] retain];
[request appendPostData:[command dataUsingEncoding:NSUTF8StringEncoding]];

request.delegate = self;
request.timeOutSeconds = 3;

if(currentRequest) {
[queuedRequest release];
queuedRequest = request;
}
else {
currentRequest = request;
[request startAsynchronous];
}
}

James: Have
you any similar plans for the future? Is this a new business for itemis?

Peter:
Yes, absolutely. Most people think itemis is just about modeling. But
actually, at 140+ employees, we’re a fairly decent consulting company.
We’ve been helping clients in various industries, ranging from
enterprise and web development to embedded development. We also offer
services for mobile application development, see http://www.itemis.com/itemis-ag/portfolio/language=en/29470/business-applications-for-mobile-devices and
we’ve got something in the pipeline which will revolutionize the market
for mobile development. Heiko: And no, it’s not
LEGO-based 😉

Heiko Behrens is a Software Architect, Eclipse committer and iPhone
developer with itemis AG. He has been writing software for as long as
he can remember. His first computer was a C64 on which he learned how
to do visual effects he later converted into stunning Demos on the x86
platform. You can read more about Heiko’s thoughts on his blog, heikobehrens.net and follow him on Twitter at @HBehrens.

Peter Friese is a Software Architect, Eclipse committer and iPhone
developer with itemis AG. His passion is to create. His first computer
was a Phillips MSX,
quickly followed by an 8086-based IBM compatible PC
with not a single but two(!) 5 1/4″ floppy drives. You can read more
about Peter on his blog, peterfriese.de and
follow him on Twitter at @peterfriese .