SlideShare a Scribd company logo
1 of 77
Download to read offline
Trayan Iliev
tiliev@iproduct.org
http://iproduct.org
Copyright © 2003-2016 IPT - Intellectual
Products & Technologies
Multi-agent Systems
and Social Robotics 2017
Reactive Robotics
& IoT - Introduction
2
Trademarks
Oracle®, Java™ and JavaScript™ are trademarks or registered
trademarks of Oracle and/or its affiliates.
LEGO® is a registered trademark of LEGO® Group. Programs are not
affiliated, sponsored or endorsed by LEGO® Education or LEGO®
Group.
Raspberry Pi™ is a trademark of Raspberry Pi Foundation.
Other names may be trademarks of their respective owners.
Tales of JAVA Robotics
3
There are several tales to share:
Tale of Robotics, IoT and Complexity
Tale of Common Sense: DDD
Tale of two cities - Imperative and Reactive
 Tale of two brave robots: LeJaRo and IPTPI
 And some real reactive Java + TypeScript / Angular 2 /
WebSocket code 
4
High Performnce Reactive JAVA
 Reactive programming. Reactor & Proactor design
patterns. Reactive Streams (java.util.concurrent.Flow)
 High performance non-blocking asynchronous apps
on JVM using Reactor project & RxJava
 Disruptor (RingBuffer), Flux & Mono, Processors
 End-to-end reactive web applications and services:
Reactor IO (REST, WebSocket) + RxJS + Angular 2
 Demo - reactive hot event streams processing on
Raspberry Pi 2 (ARM v7) based robot IPTPI.
 RxJava (not Zen only :) coans for self assessment
Where to Find the Demo Code?
5
IPTPI Reactive Demo is available @ GitHub:
https://github.com/iproduct/jprime-demo
Robots Can Be Complex
6
… Even More Complex
7
Cross-section of many
disciplines:
 mechanical engineering
 electrical engineering
 computer science
 artificial intelligence (AI)
 human-computer interaction
 sociology & psychology
Picture by Hugo Elias of the Shadow Robot Company -
http://www.shadowrobot.com/media/pictures.shtml, CC BY-SA 3.0
Engineering, Science & Art
8
Source: https://commons.wikimedia.org/w/index.php?curid=551256, CC BY-SA 3.0
and How Can We Forget
9
Source: https://commons.wikimedia.org/
w/index.php?curid=234900, CC BY-SA 3.0
Source: Korea Institute of Industrial Technology,
http://news.naver.com/main/read.nhn?
mode=LSD&mid=sec&sid1=102&oid=020&aid=0000371339
Robots: The Most Intelligent Things
10
CC BY 2.0, Source:
https://www.flickr.com/photos/wilgengebroed/8249565455/
Radar, GPS, lidar for navigation and obstacle
avoidance ( 2007 DARPA Urban Challenge )
The Internet of Things has the potential to change the
world, just as the Internet did. Maybe even more so.
 Nearly 50 petabytes of data are captured and created
by human beings
 People have limited time, attention and accuracy
 Capturing data about things in the real world in real time
 Track and count everything, reduce waste, loss & cost.
 Know when things need replacing, repairing or recalling
— Kevin Ashton, 'That 'Internet of Things' Thing', RFID Journal,
2009
Internet of Things (IoT)
 There will be nearly 26 billion devices on the Internet of
Things by 2020.
[Gartner]
 More than 30 billion devices will be wirelessly
connected to the Internet of Things by 2020
[ABI Research]
 It's expected to be a 19 Trillion USD market
[John Chambers, Cisco CEO]
IoT Perspectives
"Basket of remotes" problem – we'll have hundreds of
applications to interface with hundreds of devices that
don't share protocols for speaking with one another
[Jean-Louis Gassée, Apple initial team, and BeOS co-founder]
Only IPv6 addresses are not enough – IoT devices
should be also easily and directly accessible for users
and [their] agents
In read/write mode
Preferably using a standard web browser
Even behind firewalls
IoT - Need for Standards
IoT Services Architecture
14
Devices: Hardware + Embedded Software + Firmware
UART/ I2C/ 2G/ 3G/ LTE/ ZigBee/ 6LowPan/ BLE
Aggregation/ Bus: ESB, Message Broker
Device Gateway: Local Coordination and Event Aggregation
M2M: HTTP(/2) / WS / MQTT / CoAP
Management: TR-069 / OMA-DM / OMA LWM2M
HTTP, AMQP
Cloud (Micro)Service Mng.
Docker, Kubernetes/
Apache Brooklyn
Web/ Mobile
Portal
PaaSDashboard
PaaS API: Event Processing Services, Analytics
Tracking Complexity
15
We need tools to cope with all that complexity inherent in
robotics and IoT domains.
Simple solutions are needed – cope with problems through
divide and concur on different levels of abstraction:
Domain Driven Design (DDD) – back to basics:
domain objects, data and logic.
Described by Eric Evans in his book:
Domain Driven Design: Tackling Complexity in the Heart of
Software, 2004
Common Sense: DDD
16
Actually DDD require additional efforts (as most other
divide and concur modeling approaches :)
 Ubiquitous language and Bounded Contexts
 DDD Application Layers:
Infrastructure, Domain, Application, Presentation
 Hexagonal architecture :
OUTSIDE <-> transformer <-> ( application <-> domain )
[A. Cockburn]
Common Sense: DDD
17
Main concepts:
 Entities, value objects and modules
 Aggregates and Aggregate Roots [Haywood]:
value < entity < aggregate < module < BC
 Repositories, Factories and Services:
application services <-> domain services
 Separating interface from implementation
Imperative and Reactive
18
We live in a Connected Universe
... there is hypothesis that all
the things in the Universe are
intimately connected, and you
can not change a bit without
changing all.
Action – Reaction principle is
the essence of how Universe
behaves.
Imperative and Reactive
 Reactive Programming: using static or dynamic data
flows and propagation of change
Example: a := b + c
 Functional Programming: evaluation of mathematical
functions,
➢ Avoids changing-state and mutable data, declarative
programming
➢ Side effects free => much easier to understand and
predict the program behavior.
Example: books.stream().filter(book -> book.getYear() > 2010)
.forEach( System.out::println )
Functional Reactive (FRP)
20
According to Connal Elliot's (ground-breaking paper @
Conference on Functional Programming, 1997), FRP is:
(a) Denotative
(b) Temporally continuous
Reactive Manifesto
21
[http://www.reactivemanifesto.org]
Reactive Programming
22
 Microsoft®
opens source polyglot project ReactiveX
(Reactive Extensions) [http://reactivex.io]:
Rx = Observables + LINQ + Schedulers :)
Java: RxJava, JavaScript: RxJS, C#: Rx.NET, Scala: RxScala,
Clojure: RxClojure, C++: RxCpp, Ruby: Rx.rb, Python: RxPY,
Groovy: RxGroovy, JRuby: RxJRuby, Kotlin: RxKotlin ...
 Reactive Streams Specification
[http://www.reactive-streams.org/] used by:
 (Spring) Project Reactor [http://projectreactor.io/]
 Actor Model – Akka (Java, Scala) [http://akka.io/]
Trayan Iliev
IPT – Intellectual Products & Technologies
Ltd.
Multi-Agent
Systems & Social
Robotics
15/01/2015 Slide 23Copyright © 2003-2015 IPT – Intellectual Products & Technologies Ltd. All rights
reserved.
Подход на интелигентните агенти при
моделиране на знания и системи
Reactive Streams Spec.
24
 Reactive Streams – provides standard for
asynchronous stream processing with non-blocking
back pressure.
 Minimal set of interfaces, methods and protocols for
asynchronous data streams
 April 30, 2015: has been released version 1.0.0 of
Reactive Streams for the JVM (Java API,
Specification, TCK and implementation examples)
 Java 9: java.util.concurrent.Flow
Reactive Streams Spec.
25
 Publisher – provider of potentially unbounded number
of sequenced elements, according to Subscriber(s)
demand.
Publisher.subscribe(Subscriber) => onSubscribe onNext*
(onError | onComplete)?
 Subscriber – calls Subscription.request(long) to
receive notifications
 Subscription – one-to-one Subscriber ↔ Publisher,
request data and cancel demand (allow cleanup).
 Processor = Subscriber + Publisher
FRP = Async Data Streams
26
 FRP is asynchronous data-flow programming using the
building blocks of functional programming (e.g. map,
reduce, filter) and explicitly modeling time
 Used for GUIs, robotics, and music. Example (RxJava):
Observable.from(new String[]{"Reactive",
"Extensions", "Java"})
.take(2).map(s -> s + " : on " + new Date())
.subscribe(s -> System.out.println(s));
Result:
Reactive : on Wed Jun 17 21:54:02 GMT+02:00 2015
Extensions : on Wed Jun 17 21:54:02 GMT+02:00 2015
27
 Performance is about 2 things (Martin Thompson –
http://www.infoq.com/articles/low-latency-vp ):
– Throughput – units per second, and
– Latency – response time
 Real-time – time constraint from input to response
regardless of system load.
 Hard real-time system if this constraint is not honored then
a total system failure can occur.
 Soft real-time system – low latency response with little
deviation in response time
 100 nano-seconds to 100 milli-seconds. [Peter Lawrey]
What About High Performance?
28
 Mechanical Sympathy – hardware (CPU, cache, memory,
IO, Network), operating system, language implementation
platform (e.g. JVM), and application level code are working
in harmony to minimize the time needed for event (request,
message) processing => 10% / 90% principle
 Throughput vs. latency – bus vs. car traveling
 Throughput ~ System Capacity / Latency
 Achieving low latency may mean additional work done
by system => lowered System Capacity and Throughput
 Horizontal scalability is valuable for high throughput. For
low latency, you need simplicity – critical path.
Throughput vs. Latency
29
 JVMs can be faster than custom C++ code because of the
holistic optimizations that they can apply across an application
[Andy Piper].
 Developers can take advantage of hardware guarantees through
a detailed understanding of:
– Java Memory Model & mapping to underlying hardware
– low latency software system hardware (CPU, cache, memory,
IO, Network)
– avoiding lock-contention and garbage collection
– Compre-And-Swap – CAS (java.util.concurrent.atomic)
– lock-free, wait-free techniques – using standard libraries (e.g.
the LMAX Disruptor)
High Performance Java
30
CPU Cache – False Sharing
Core 2 Core NCore 1 ...
Registers
Execution Units
L1 Cache A | | B |
L2 Cache A | | B |
L3 Cache A | | B |
DRAM Memory
A | | B |
Registers
Execution Units
L1 Cache A | | B |
L2 Cache A | | B |
31
 Low garbage by reusing existing objects + infrequent GC
when application not busy – can improve app 2 - 5x
 JVM generational GC startegy – ideal for objects living very
shortly (garbage collected next minor sweep) or be immortal
 Non-blocking, lockless coding or CAS
 Critical data structures – direct memory access using
DirectByteBuffers or Unsafe => predictable memory layout
and cache misses avoidance
 Busy waiting – giving the CPU to OS kernel slows program
2-5x => avoid context switches
 Amortize the effect of expensive IO - blocking
Low Latency: Things to Remember
32
 Parallel tasks can increase your throughput by increasing
system capacity – it is GOOD!
 But comes together with concurrent access to shared
resources => you have to provide mutual exclusion (MutEx)
by parallel threads when changing the resources' state (read
only access can be shared by multiple threads)
 Mutual exclusion can be achieved in several ways:
– synchronized – hardwired in HotSpot JVM, optimized in J^6
– ReentrantLock, ReadWriteLock, StampedLock →
java.util.concurrent.locks.*
– Optimistic Locking → tryLock(), CAS
Parallelism & Concurrency
33
Simple problem: incrementing a long value 500 000 000 times.
9 implementations:
‒ SynchronousCounter – while (counter++ < 500000000){}
‒ SingleThreadSynchronizedCounter – 1T using synchronized
‒ TwoThreadsSynchronizedCounter – 2T using synchronized
‒ SingleThreadCASCounter – 1T using AtomicLong
‒ TwoThreadsCASCounter – 2T using AtomicLong
‒ TwoThreadsCASCounterLongAdder – 1T using LongAdder
‒ SingleThreadVolatileCounter – 1T, memory barrier (volatile)
‒ TwoThreadsVolatileCounter – 2T, memory barrier (volatile)
Comparing Concurrent Impl.
34
Test results (on my laptop - quad core Intel i7@2.2GHz):
− SynchronousCounter – 190ms
− SingleThreadSynchronizedCounter – 15000 ms
− TwoThreadsSynchronizedCounter – 21000 ms
− SingleThreadCASCounter – 4100 ms
− TwoThreadsCASCounter – 12000 ms
− TwoThreadsCASCounterLongAdder – 12800 ms
− SingleThreadVolatileCounter – 4100 ms
− TwoThreadsVolatileCounter – 20000 ms
Comparing Concurrent Impl.
35
For more complete micro-benchmarking of
different Mutex implementations see:
http://blog.takipi.com/java-8-stampedlocks-vs-
readwritelocks-and-synchronized/
http://www.slideshare.net/haimyadid/java-8-
stamped-lock
Comparing Concurrent Impl.
36
 Non-blocking (synchronous) implementation is 2 orders of
magnitude better then synchronized
 We should try to avoid blocking and especially contended
blocking if want to achieve low latency
 If blocking is a must we have to prefer CAS and optimistic
concurrency over blocking (but have in mind it always
depends on concurrent problem at hand and how much
contention do we experience – test early, test often,
microbenchmarks are unreliable and highly platform dependent
– test real application with typical load patterns)
 The real question is: HOW is is possible to build concurrency
without blocking?
Mutex Comparison => Conclusions
37
 Message Driven – asynchronous message-passing allows
to establish a boundary between components that ensures
loose coupling, isolation, location transparency, and
provides the means to delegate errors as messages
[Reactive Manifesto].
 The main idea is to separate concurrent producer and
consumer workers by using message queues.
 Message queues can be unbounded or bounded (limited
max number of messages)
 Unbounded message queues can present memory
allocation problem in case the producers outrun the
consumers for a long period → OutOfMemoryError
Scalable, Massively Concurrent
38
 Queues typically use either linked-lists or arrays for the
underlying storage of elements. Linked lists are not
„mechanically sympathetic” – there is no predictable
caching “stride” (should be less than 2048 bytes in each
direction).
 Bounded queues often experience write contention on
head, tail, and size variables. Even if head and tail
separated using CAS, they usually are in the same cache-
line.
 Queues produce much garbage.
 Typical queues conflate a number of different concerns –
producer and consumer synchronization and data storage
Queues Disadvantages
[http://lmax-exchange.github.com/disruptor/files/Disruptor-1.0.pdf]
39
 LMAX Disruptor design pattern separates different
concerns in a “mechanically sympathetic” way:
- Storage of items being exchanged
- Producer coordination – claiming the next sequence
- Consumers coordination – notified new item is available
 Single Writer principle is employed when writing data in
the Ring Buffer from single producer thread only (no
contention),
 When multiple producers → CAS
 Memory pre-allocated – predictable stride, no garbage
LMAX Disruptor (RingBuffer)
[http://lmax-exchange.github.com/disruptor/files/Disruptor-1.0.pdf]
40
LMAX Disruptor (RingBuffer) High Performance
[http://lmax-exchange.github.com/disruptor/files/Disruptor-
1.0.pdf]
Source: LMAX Disruptor github wiki - https://raw.githubusercontent.com/wiki/LMAX-
Exchange/disruptor/images/Models.png
LMAX-Exchange Disruptor License @ GitHub: Apache License Version 2.0, January 2004 -
http://www.apache.org/licenses/
41
LMAX Disruptor (RingBuffer) High Performance
[http://lmax-exchange.github.com/disruptor/files/Disruptor-
1.0.pdf]
Source: LMAX Disruptor @ GitHub - https://github.com/LMAX-
Exchange/disruptor/blob/master/docs/Disruptor.docx
LMAX-Exchange Disruptor License @ GitHub: Apache License Version 2.0, January 2004 -
http://www.apache.org/licenses/
Project Reactor
42
 Reactor project allows building high-performance (low
latency high throughput) non-blocking asynchronous
applications on JVM.
 Reactor is designed to be extraordinarily fast and can
sustain throughput rates on order of 10's of millions of
operations per second.
 Reactor has powerful API for declaring data
transformations and functional composition.
 Makes use of the concept of Mechanical Sympathy
built on top of Disruptor / RingBuffer.
Project Reactor
43
 Pre-allocation at startup-time
 Message-passing structures are bounded
 Using Reactive and Event-Driven Architecture patterns
=> non-blocking end-to-end flows, replies
 Implement Reactive Streams Specification – efficient
bounded structures requesting no more than capacity
 Applies above features to IPC and provides non-
blocking IO drivers that are flow-control aware
 Expose a Functional API – organize their code in a
side-effect free way, which helps you determine you are
thread-safe and fault-tolerant
Reactor Projects
44
https://github.com/reactor/reactor, Apache Software License 2.0
IPC – Netty, Kafka, Aeron
Reactor Projects
45
Reactor Flux
46
https://github.com/reactor/reactor-core, Apache Software License 2.0
Reactor Mono
47
https://github.com/reactor/reactor-core, Apache Software License 2.0
Example: Flux.combineLatest()
48
https://projectreactor.io/core/docs/api/, Apache Software License 2.0
Reactor: Hello World
49
public static void main(String... args) throws
InterruptedException {
EmitterProcessor<String> emitter =
EmitterProcessor.create();
BlockingSink<String> sink = emitter.connectSink();
emitter.publishOn(Schedulers.single())
.map(String::toUpperCase)
.filter(s → s.startsWith("HELLO"))
.delayMillis(1000).subscribe(System.out::println);
sink.submit("Hello World!"); // emit - non blocking
sink.submit("Goodbye World!");
sink.submit("Hello Trayan!");
Thread.sleep(3000);
}
Reactor: Flux Example
50
Flux.fromIterable(getSomeLongList())
.mergeWith(Flux.interval(100))
.doOnNext(serviceA::someObserver)
.map(d -> d * 2)
.take(3)
.onErrorResumeWith(errorHandler::fallback)
.doAfterTerminate(serviceM::incrementTerminate)
.subscribe(System.out::println);
https://github.com/reactor/reactor-core, Apache Software License 2.0
Reactor Bus: IPTPI Java Robot
51
Disruptor (Ring Buffer) used in Reactor
52
Reactor provides 3 major types of Processors:
 EmitterProcessor – using 0 threads (on same thread)
 TopicProcessor using – N threads concurrently
processing the messages (AND operation)
 WorkQueueProcessor – N threads alternatively
processing the messages (XOR operation – messages
are processed exactly by one thread – load ballancing
and work distribution)
53
Meet IPTPI :)
54
Ups...
IPTPI: RPi2 + Ardunio Robot
55
 Raspberry Pi 2 (quad-core ARMv7
@ 900MHz) + Arduino Leonardo
cloneA-Star 32U4 Micro
 Optical encoders (custom), IR
optical array, 3D accelerometers,
gyros, and compass MinIMU-9 v2
 IPTPI is programmed in Java
using Pi4J, Reactor, RxJava, Akka
 More information about IPTPI:
http://robolearn.org/iptpi-robot/
IPTPI: RPi2 + Ardunio Robot
56
3D accelerometers, gyros,
and compass MinIMU-9 v2
Pololu DRV8835
Dual Motor Driver
for Raspberry Pi
Arduino Leonardo clone
A-Star 32U4 Micro
USB Stereo
Speakers - 5V
LiPo Powebank
15000 mAh
IPTPI: RPi2 + Ardunio Robot
57
Raspberry Pi 2 (quad-core
ARMv7 @ 900MHz)
IR Optical Sensor QRD1114
Array (Line Following)
Adafruit 2.8" PiTFT -
Capacitive Touch Screen
58
LeJaRo: Lego®
Java Robot
59
 Modular – 3 motors (with encoders) – one driving each
track, and third for robot clamp.
 Three sensors: touch sensor (obstacle avoidance), light
color sensor (follow line), IR sensor (remote).
 LeJaRo is programmed in Java using LeJOS library.
 More information about LeJaRo:
http://robolearn.org/lejaro/
 Programming examples available @GitHub:
https://github.com/iproduct/course-social-robotics/tre
e/master/motors_demo
LEGO® is a registered trademark of LEGO® Group. Programs of IPT are not
affiliated, sponsored or endorsed by LEGO® Education or LEGO® Group.
Tale of Simplicity: DDD
60
IPTPI Reactive Streams
61
Encoder
Readings
ArduinoData
Fluxion
Arduino
SerialData
Position
Fluxion
Robot
Positions
Command
Movement
Subscriber
RobotWSService
(using Reactor)
Angular 2 /
TypeScript
MovementCommands
IPTPI: IPTPIDemo I
62
public class IPTPIVDemo {
...
public IPTPIDemo() {
//receive Arduino data readings
ArduinoData =
ArduinoFactory.getInstance().createArduinoData();
//calculate robot positions
PositionsFlux = PositionFactory.createPositionFlux(
arduinoData.getEncoderReadingsFlux());
resentationViews.add(
PositionFactory.createPositionPanel(positionsFlux));
//enable sending commands to Arduino
ArduinoCommandsSub = ArduinoFactory.getInstance()
.createArduinoCommandSubscriber();
/
IPTPI: IPTPIDemo II
63
//Audio player - added @jPrime 2016 Hackergarten
audio = AudioFactory.createAudioPlayer();
//wire robot main controller with services
movementSub =MovementFactory.createMovementCommandSubscriber(
positionsFlux, arduinoData.getLineReadingsFlux());
controller = new RobotController(this::tearDown, movementSub,
arduinoCommandsSub, audio);
//create view with controller and delegate material views
from query services
view = new RobotView("IPTPI Reactive Robotics Demo",
controller, presentationViews);
IPTPI: IPTPIDemo III
64
//expose as WS service
movementSub2 =MovementFactory.createMovementCommandSubscriber(
positionsFlux, arduinoData.getLineReadingsFlux());
positionsService = new RobotWSService(
positionsFlux, movementSub2);
}
public static void main(String[] args) {
// initialize wiringPi library
Gpio.wiringPiSetupGpio();
try {
IPTPIDemo demo = new IPTPIDemo();
} catch (IOException e) {
e.printStackTrace();
}
}
IPTPI: ArduinoData I
65
positionsFlux = EmitterProcessor.create();
positionsSink = positionsFlux.connectSink();
lineFlux = EmitterProcessor.create();
lineSink = lineFlux.connectSink();
final Serial serial = SerialFactory.createInstance();
serial.addListener(new SerialDataEventListener() {
private ByteBuffer buffer = ByteBuffer.allocate(1024);
public void dataReceived(SerialDataEvent event) {
try {
ByteBuffer newBuffer = event.getByteBuffer();
buffer.put(newBuffer); buffer.flip();
...
buffer.get();
long timestamp = buffer.getInt(); //get timestamp
int encoderL = -buffer.getInt(); //motors mirrored
int encoderR = buffer.getInt();
IPTPI: ArduinoData II
66
EncoderReadings readings =
new EncoderReadings(encoderR, encoderL, timestamp);
emitter.submit(readings);
...
buffer.compact();
} catch (Exception e) {
e.printStackTrace();
}
}
});
try {
serial.open(PORT, 38400);
} catch(SerialPortException | IOException ex) {
System.out.println(“SERIAL SETUP FAILED:"+ex.getMessage());
}
IPTPI: PositionFlux I
67
Redux
Pattern!
public PositionsFlux(
Flux<EncoderReadings> readingsFlux) {
this.encoderReadings = readingsFlux;
Flux<EncoderReadings> skip1 = readingsFlux.skip(1);
positionsFlux = Flux.zip(readingsFlux, skip1)
.map(tupple ->
.scan(new Position(0, 0, 0), (last, tupple) -> {
EncoderReadings prev = tupple.getT1();
EncoderReadings curr = tupple.getT2();
int prevL = prev.getEncoderL();
int prevR = prev.getEncoderR();
int currL = curr.getEncoderL();
int currR = curr.getEncoderR();
int sL = currL - prevL;
int sR = currR - prevR;
double alpha0 = last.getHeading();
IPTPI: PositionFlux II
68
double alpha0 = last.getHeading();
if(sR == sL) {
return new Position((float)(last.getX() + sL *
ENCODER_STEP_LENGTH * cos(alpha0)),
(float)(last.getY()+ sL * ENCODER_STEP_LENGTH *
sin(alpha0)), alpha0, curr.getTimestamp());
} else {
…
}
})
);
}
CommandMovementSubscriber I
69
public class CommandMovementSubscriber extends
ConsumerSubscriber<Command<Movement>> {
private PositionFluxion positions;
public CommandMovementSubscriber(PositionFluxion positions){
this.positions = positions;
Gpio.wiringPiSetupGpio(); // initialize wiringPi library
Gpio.pinMode(5, Gpio.OUTPUT); // Motor direction pins
Gpio.pinMode(6, Gpio.OUTPUT);
Gpio.pinMode(12, Gpio.PWM_OUTPUT); // Motor speed pins
Gpio.pinMode(13, Gpio.PWM_OUTPUT);
Gpio.pwmSetMode(Gpio.PWM_MODE_MS);
Gpio.pwmSetRange(MAX_SPEED);
Gpio.pwmSetClock(CLOCK_DIVISOR);
}
@Override
public void doNext(Command<Movement> command) { ... }
}
CommandMovementSubscriber II
70
private void runMotors(MotorsCommand mc) {
//setting motor directions
Gpio.digitalWrite(5, mc.getDirR() > 0 ? 1 : 0);
Gpio.digitalWrite(6, mc.getDirL() > 0 ? 1 : 0);
//setting speed
if(mc.getVelocityR()>=0 && mc.getVelocityR() <=MAX_SPEED)
Gpio.pwmWrite(12, mc.getVelocityR()); // set speed
if(mc.getVelocityL()>=0 && mc.getVelocityL() <=MAX_SPEED)
Gpio.pwmWrite(13, mc.getVelocityL());
}
}
Reactor IO – NetStreams API
71
http://projectreactor.io/io/docs/reference/, Apache License 2.0
Takeaways: Why Go Reactive?
72
Benefits using Reactive Programming + DDD:
 DDD helps to manage complexity in IoT and Robotics -
many subsystems = sub-domains
 Reactive Streams (Fluxes, Monos) = uni-directional data
flows, CQRS, event sourcing, microservices
 Reactive Streams can be non-blocking and highly
efficient, or can utilize blocking if needed
 Naturally implement state management patterns like
Redux, allow time travel, replay and data analytics
 Clear, declarative data transforms that scale (Map-
Reduce, BigData, PaaS)
Takeaways: Why Maybe Not?
73
Cons using Reactive Programming + DDD:
 DDD requires additional efforts to clearly separate
different (sub) domains – DSL translators, factories...
 Reactive Streams utilize functional composition and
require entirely different mindset then imperative – feels
like learning foreign language
 Pure functions and Redux provide much benefits,
but there's always temptation to “do it the old way” :)
 Tool support for functional programming in Java is still
not perfect (in Eclipse at least :)
Where to Find the Demo Code?
74
IPTPI Reactive Demo is available @ GitHub:
https://github.com/iproduct/jprime-demo
75
Resources: RxMarbles & Rx Coans
RxMarbles:
http://rxmarbles.com/
RxJava Koans – Let's try to solve them at:
https://github.com/mutexkid/rxjava-koans
RxJS Koans – for those who prefer JavaScript :)
https://github.com/Reactive-Extensions/RxJSKoans
Tale of Simplicity: DDD
76
http://robolearn.org/ Let's move!
http://iproduct.org/
Thank’s for Your Attention!
77
Trayan Iliev
CEO of IPT – Intellectual Products
& Technologies
http://iproduct.org/
http://robolearn.org/
https://github.com/iproduct
https://twitter.com/trayaniliev
https://www.facebook.com/IPT.EACAD
https://plus.google.com/+IproductOrg

More Related Content

What's hot

Real-Time Cloud Robotics in Practical Smart City Applications
Real-Time Cloud Robotics in Practical Smart City ApplicationsReal-Time Cloud Robotics in Practical Smart City Applications
Real-Time Cloud Robotics in Practical Smart City ApplicationsC2RO Cloud Robotics
 
Hire a Machine to Code - Michael Arthur Bucko & Aurélien Nicolas
Hire a Machine to Code - Michael Arthur Bucko & Aurélien NicolasHire a Machine to Code - Michael Arthur Bucko & Aurélien Nicolas
Hire a Machine to Code - Michael Arthur Bucko & Aurélien NicolasWithTheBest
 
On premise ai platform - from dc to edge
On premise ai platform - from dc to edgeOn premise ai platform - from dc to edge
On premise ai platform - from dc to edgeConference Papers
 
Implementing AI: Running AI at the Edge: Embedding low-cost intelligence with...
Implementing AI: Running AI at the Edge: Embedding low-cost intelligence with...Implementing AI: Running AI at the Edge: Embedding low-cost intelligence with...
Implementing AI: Running AI at the Edge: Embedding low-cost intelligence with...KTN
 
NVIDIA Deep Learning Institute 2017 基調講演
NVIDIA Deep Learning Institute 2017 基調講演NVIDIA Deep Learning Institute 2017 基調講演
NVIDIA Deep Learning Institute 2017 基調講演NVIDIA Japan
 
Tales of AI agents saving the human race!
Tales of AI agents saving the human race!Tales of AI agents saving the human race!
Tales of AI agents saving the human race!Alison B. Lowndes
 
Adaptive Neighbor Discovery for Mobile and Low Power Wireless Sensor Networks
Adaptive Neighbor Discovery for Mobile and Low Power Wireless Sensor Networks Adaptive Neighbor Discovery for Mobile and Low Power Wireless Sensor Networks
Adaptive Neighbor Discovery for Mobile and Low Power Wireless Sensor Networks Dimitrios Amaxilatis
 
【1110ROS社群開講】ROS 2與DDS應用於工業領域_王健豪
【1110ROS社群開講】ROS 2與DDS應用於工業領域_王健豪【1110ROS社群開講】ROS 2與DDS應用於工業領域_王健豪
【1110ROS社群開講】ROS 2與DDS應用於工業領域_王健豪MAKERPRO.cc
 
Fuelling the AI Revolution with Gaming
Fuelling the AI Revolution with GamingFuelling the AI Revolution with Gaming
Fuelling the AI Revolution with GamingAlison B. Lowndes
 
PGI Compilers & Tools Update- March 2018
PGI Compilers & Tools Update- March 2018PGI Compilers & Tools Update- March 2018
PGI Compilers & Tools Update- March 2018NVIDIA
 
Implementing AI: Running AI at the Edge: Adapting AI to available resource in...
Implementing AI: Running AI at the Edge: Adapting AI to available resource in...Implementing AI: Running AI at the Edge: Adapting AI to available resource in...
Implementing AI: Running AI at the Edge: Adapting AI to available resource in...KTN
 
Talk on using AI to address some of humanities problems
Talk on using AI to address some of humanities problemsTalk on using AI to address some of humanities problems
Talk on using AI to address some of humanities problemsAlison B. Lowndes
 
Accelerating open science and AI with automated, portable, customizable and r...
Accelerating open science and AI with automated, portable, customizable and r...Accelerating open science and AI with automated, portable, customizable and r...
Accelerating open science and AI with automated, portable, customizable and r...Grigori Fursin
 
AI For Enterprise
AI For EnterpriseAI For Enterprise
AI For EnterpriseNVIDIA
 
Implementing AI: Running AI at the Edge: ClickCV – Providing high-performance...
Implementing AI: Running AI at the Edge: ClickCV – Providing high-performance...Implementing AI: Running AI at the Edge: ClickCV – Providing high-performance...
Implementing AI: Running AI at the Edge: ClickCV – Providing high-performance...KTN
 
Intel IT OpenStack Journey - OpenStack Fall 2012 Summit.pdf
Intel IT OpenStack Journey - OpenStack Fall 2012 Summit.pdfIntel IT OpenStack Journey - OpenStack Fall 2012 Summit.pdf
Intel IT OpenStack Journey - OpenStack Fall 2012 Summit.pdfOpenStack Foundation
 
NVIDIA Is Revolutionizing Computing - June 2017
NVIDIA Is Revolutionizing Computing - June 2017 NVIDIA Is Revolutionizing Computing - June 2017
NVIDIA Is Revolutionizing Computing - June 2017 NVIDIA
 

What's hot (20)

Real-Time Cloud Robotics in Practical Smart City Applications
Real-Time Cloud Robotics in Practical Smart City ApplicationsReal-Time Cloud Robotics in Practical Smart City Applications
Real-Time Cloud Robotics in Practical Smart City Applications
 
Hire a Machine to Code - Michael Arthur Bucko & Aurélien Nicolas
Hire a Machine to Code - Michael Arthur Bucko & Aurélien NicolasHire a Machine to Code - Michael Arthur Bucko & Aurélien Nicolas
Hire a Machine to Code - Michael Arthur Bucko & Aurélien Nicolas
 
On premise ai platform - from dc to edge
On premise ai platform - from dc to edgeOn premise ai platform - from dc to edge
On premise ai platform - from dc to edge
 
Implementing AI: Running AI at the Edge: Embedding low-cost intelligence with...
Implementing AI: Running AI at the Edge: Embedding low-cost intelligence with...Implementing AI: Running AI at the Edge: Embedding low-cost intelligence with...
Implementing AI: Running AI at the Edge: Embedding low-cost intelligence with...
 
NVIDIA Deep Learning Institute 2017 基調講演
NVIDIA Deep Learning Institute 2017 基調講演NVIDIA Deep Learning Institute 2017 基調講演
NVIDIA Deep Learning Institute 2017 基調講演
 
Phi Week 2019
Phi Week 2019Phi Week 2019
Phi Week 2019
 
Tales of AI agents saving the human race!
Tales of AI agents saving the human race!Tales of AI agents saving the human race!
Tales of AI agents saving the human race!
 
Adaptive Neighbor Discovery for Mobile and Low Power Wireless Sensor Networks
Adaptive Neighbor Discovery for Mobile and Low Power Wireless Sensor Networks Adaptive Neighbor Discovery for Mobile and Low Power Wireless Sensor Networks
Adaptive Neighbor Discovery for Mobile and Low Power Wireless Sensor Networks
 
NVIDIA DataArt IT
NVIDIA DataArt ITNVIDIA DataArt IT
NVIDIA DataArt IT
 
EPSRC CDT Conference
EPSRC CDT ConferenceEPSRC CDT Conference
EPSRC CDT Conference
 
【1110ROS社群開講】ROS 2與DDS應用於工業領域_王健豪
【1110ROS社群開講】ROS 2與DDS應用於工業領域_王健豪【1110ROS社群開講】ROS 2與DDS應用於工業領域_王健豪
【1110ROS社群開講】ROS 2與DDS應用於工業領域_王健豪
 
Fuelling the AI Revolution with Gaming
Fuelling the AI Revolution with GamingFuelling the AI Revolution with Gaming
Fuelling the AI Revolution with Gaming
 
PGI Compilers & Tools Update- March 2018
PGI Compilers & Tools Update- March 2018PGI Compilers & Tools Update- March 2018
PGI Compilers & Tools Update- March 2018
 
Implementing AI: Running AI at the Edge: Adapting AI to available resource in...
Implementing AI: Running AI at the Edge: Adapting AI to available resource in...Implementing AI: Running AI at the Edge: Adapting AI to available resource in...
Implementing AI: Running AI at the Edge: Adapting AI to available resource in...
 
Talk on using AI to address some of humanities problems
Talk on using AI to address some of humanities problemsTalk on using AI to address some of humanities problems
Talk on using AI to address some of humanities problems
 
Accelerating open science and AI with automated, portable, customizable and r...
Accelerating open science and AI with automated, portable, customizable and r...Accelerating open science and AI with automated, portable, customizable and r...
Accelerating open science and AI with automated, portable, customizable and r...
 
AI For Enterprise
AI For EnterpriseAI For Enterprise
AI For Enterprise
 
Implementing AI: Running AI at the Edge: ClickCV – Providing high-performance...
Implementing AI: Running AI at the Edge: ClickCV – Providing high-performance...Implementing AI: Running AI at the Edge: ClickCV – Providing high-performance...
Implementing AI: Running AI at the Edge: ClickCV – Providing high-performance...
 
Intel IT OpenStack Journey - OpenStack Fall 2012 Summit.pdf
Intel IT OpenStack Journey - OpenStack Fall 2012 Summit.pdfIntel IT OpenStack Journey - OpenStack Fall 2012 Summit.pdf
Intel IT OpenStack Journey - OpenStack Fall 2012 Summit.pdf
 
NVIDIA Is Revolutionizing Computing - June 2017
NVIDIA Is Revolutionizing Computing - June 2017 NVIDIA Is Revolutionizing Computing - June 2017
NVIDIA Is Revolutionizing Computing - June 2017
 

Viewers also liked

Robotic Surgery - Dr. Meenakshi Sundaram
Robotic Surgery - Dr. Meenakshi SundaramRobotic Surgery - Dr. Meenakshi Sundaram
Robotic Surgery - Dr. Meenakshi SundaramApollo Hospitals
 
Robotic Surgery by muthugomathy and meenakshi shetti.
Robotic Surgery by muthugomathy and meenakshi shetti.Robotic Surgery by muthugomathy and meenakshi shetti.
Robotic Surgery by muthugomathy and meenakshi shetti.Qualcomm
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerLuminary Labs
 
Hackathon: “IPTPI and LeJaRo Meet The Real World”
Hackathon: “IPTPI and LeJaRo Meet The Real World”Hackathon: “IPTPI and LeJaRo Meet The Real World”
Hackathon: “IPTPI and LeJaRo Meet The Real World”Trayan Iliev
 
Adding Value To Your Strategic Partnerships
Adding Value To Your Strategic PartnershipsAdding Value To Your Strategic Partnerships
Adding Value To Your Strategic PartnershipsThom. Poole
 
Leadership of Open Innovation by Paul Sloane
Leadership of Open Innovation by Paul SloaneLeadership of Open Innovation by Paul Sloane
Leadership of Open Innovation by Paul Sloane★ Tony Karrer
 
Robots in automobile industry
Robots in automobile industryRobots in automobile industry
Robots in automobile industryNiraj Rajan
 
Smart machines -esitys Tampereella 02/2016
Smart machines -esitys Tampereella 02/2016Smart machines -esitys Tampereella 02/2016
Smart machines -esitys Tampereella 02/2016Immo Salo
 
introduction to Raspberry pi
introduction to Raspberry pi introduction to Raspberry pi
introduction to Raspberry pi Mohamed Ali May
 
"Curious Learning: using a mobile platform for early literacy education as a ...
"Curious Learning: using a mobile platform for early literacy education as a ..."Curious Learning: using a mobile platform for early literacy education as a ...
"Curious Learning: using a mobile platform for early literacy education as a ...diannepatricia
 
Deep Dreaming of AI in Education - BETT 2017
Deep Dreaming of AI in Education - BETT 2017Deep Dreaming of AI in Education - BETT 2017
Deep Dreaming of AI in Education - BETT 2017Martin Hamilton
 
Coffee & Pi - Intro to Pi Workshop
Coffee & Pi - Intro to Pi WorkshopCoffee & Pi - Intro to Pi Workshop
Coffee & Pi - Intro to Pi WorkshopBrad ☼ Derstine
 
Prototype Summer School: How to make an interactive light display
Prototype Summer School: How to make an interactive light displayPrototype Summer School: How to make an interactive light display
Prototype Summer School: How to make an interactive light displayNeil Winterburn
 
Smart machines - The Next Hype
Smart machines - The Next HypeSmart machines - The Next Hype
Smart machines - The Next HypeImmo Salo
 
30 Big Tech Predictions for 2017
30 Big Tech Predictions for 201730 Big Tech Predictions for 2017
30 Big Tech Predictions for 2017Filipp Paster
 

Viewers also liked (20)

Robotic Surgery - Dr. Meenakshi Sundaram
Robotic Surgery - Dr. Meenakshi SundaramRobotic Surgery - Dr. Meenakshi Sundaram
Robotic Surgery - Dr. Meenakshi Sundaram
 
Robotic Surgery by muthugomathy and meenakshi shetti.
Robotic Surgery by muthugomathy and meenakshi shetti.Robotic Surgery by muthugomathy and meenakshi shetti.
Robotic Surgery by muthugomathy and meenakshi shetti.
 
Robotic surgery
Robotic surgeryRobotic surgery
Robotic surgery
 
robotics in medical science
robotics in medical sciencerobotics in medical science
robotics in medical science
 
Hype vs. Reality: The AI Explainer
Hype vs. Reality: The AI ExplainerHype vs. Reality: The AI Explainer
Hype vs. Reality: The AI Explainer
 
Hackathon: “IPTPI and LeJaRo Meet The Real World”
Hackathon: “IPTPI and LeJaRo Meet The Real World”Hackathon: “IPTPI and LeJaRo Meet The Real World”
Hackathon: “IPTPI and LeJaRo Meet The Real World”
 
Adding Value To Your Strategic Partnerships
Adding Value To Your Strategic PartnershipsAdding Value To Your Strategic Partnerships
Adding Value To Your Strategic Partnerships
 
Leadership of Open Innovation by Paul Sloane
Leadership of Open Innovation by Paul SloaneLeadership of Open Innovation by Paul Sloane
Leadership of Open Innovation by Paul Sloane
 
Robotics –The Future of Mankind
Robotics –The Future of MankindRobotics –The Future of Mankind
Robotics –The Future of Mankind
 
Robots in automobile industry
Robots in automobile industryRobots in automobile industry
Robots in automobile industry
 
Smart machines -esitys Tampereella 02/2016
Smart machines -esitys Tampereella 02/2016Smart machines -esitys Tampereella 02/2016
Smart machines -esitys Tampereella 02/2016
 
Robots in-retail 2016-10-14
Robots in-retail 2016-10-14Robots in-retail 2016-10-14
Robots in-retail 2016-10-14
 
introduction to Raspberry pi
introduction to Raspberry pi introduction to Raspberry pi
introduction to Raspberry pi
 
"Curious Learning: using a mobile platform for early literacy education as a ...
"Curious Learning: using a mobile platform for early literacy education as a ..."Curious Learning: using a mobile platform for early literacy education as a ...
"Curious Learning: using a mobile platform for early literacy education as a ...
 
Deep Dreaming of AI in Education - BETT 2017
Deep Dreaming of AI in Education - BETT 2017Deep Dreaming of AI in Education - BETT 2017
Deep Dreaming of AI in Education - BETT 2017
 
Robotics, IOT &amp; AI
Robotics, IOT &amp; AIRobotics, IOT &amp; AI
Robotics, IOT &amp; AI
 
Coffee & Pi - Intro to Pi Workshop
Coffee & Pi - Intro to Pi WorkshopCoffee & Pi - Intro to Pi Workshop
Coffee & Pi - Intro to Pi Workshop
 
Prototype Summer School: How to make an interactive light display
Prototype Summer School: How to make an interactive light displayPrototype Summer School: How to make an interactive light display
Prototype Summer School: How to make an interactive light display
 
Smart machines - The Next Hype
Smart machines - The Next HypeSmart machines - The Next Hype
Smart machines - The Next Hype
 
30 Big Tech Predictions for 2017
30 Big Tech Predictions for 201730 Big Tech Predictions for 2017
30 Big Tech Predictions for 2017
 

Similar to Reactive robotics io_t_2017

Reactive Java Robotics IoT - jPrime 2016
Reactive Java Robotics IoT - jPrime 2016Reactive Java Robotics IoT - jPrime 2016
Reactive Java Robotics IoT - jPrime 2016Trayan Iliev
 
Reactive Microservices with Spring 5: WebFlux
Reactive Microservices with Spring 5: WebFlux Reactive Microservices with Spring 5: WebFlux
Reactive Microservices with Spring 5: WebFlux Trayan Iliev
 
Reactive Java Robotics & IoT with Spring Reactor
Reactive Java Robotics & IoT with Spring ReactorReactive Java Robotics & IoT with Spring Reactor
Reactive Java Robotics & IoT with Spring ReactorTrayan Iliev
 
IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016Trayan Iliev
 
NGRX Apps in Depth
NGRX Apps in DepthNGRX Apps in Depth
NGRX Apps in DepthTrayan Iliev
 
Microservices with Spring 5 Webflux - jProfessionals
Microservices  with Spring 5 Webflux - jProfessionalsMicroservices  with Spring 5 Webflux - jProfessionals
Microservices with Spring 5 Webflux - jProfessionalsTrayan Iliev
 
Spring 5 Webflux - Advances in Java 2018
Spring 5 Webflux - Advances in Java 2018Spring 5 Webflux - Advances in Java 2018
Spring 5 Webflux - Advances in Java 2018Trayan Iliev
 
Making Machine Learning Easy with H2O and WebFlux
Making Machine Learning Easy with H2O and WebFluxMaking Machine Learning Easy with H2O and WebFlux
Making Machine Learning Easy with H2O and WebFluxTrayan Iliev
 
Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9Trayan Iliev
 
IT TRENDS AND PERSPECTIVES 2016
IT TRENDS AND PERSPECTIVES 2016IT TRENDS AND PERSPECTIVES 2016
IT TRENDS AND PERSPECTIVES 2016Vaidheswaran CS
 
Fog Computing - DEV.BG 2018
Fog Computing - DEV.BG 2018Fog Computing - DEV.BG 2018
Fog Computing - DEV.BG 2018Trayan Iliev
 
Cytoscape CI Chapter 2
Cytoscape CI Chapter 2Cytoscape CI Chapter 2
Cytoscape CI Chapter 2bdemchak
 
StrongLoop Overview
StrongLoop OverviewStrongLoop Overview
StrongLoop OverviewShubhra Kar
 
React Native e IoT - Un progetto complesso
React Native e IoT - Un progetto complessoReact Native e IoT - Un progetto complesso
React Native e IoT - Un progetto complessoCommit University
 
Building Robotics Application at Scale using OpenSource from Zero to Hero
Building Robotics Application at Scale using OpenSource from Zero to HeroBuilding Robotics Application at Scale using OpenSource from Zero to Hero
Building Robotics Application at Scale using OpenSource from Zero to HeroAlex Barbosa Coqueiro
 
N01 cloud computing_and_gae
N01 cloud computing_and_gaeN01 cloud computing_and_gae
N01 cloud computing_and_gaeSun-Jin Jang
 
FIWARE Wednesday Webinars - How to Develop FIWARE NGSI Interfaces for Robots
FIWARE Wednesday Webinars - How to Develop FIWARE NGSI Interfaces for RobotsFIWARE Wednesday Webinars - How to Develop FIWARE NGSI Interfaces for Robots
FIWARE Wednesday Webinars - How to Develop FIWARE NGSI Interfaces for RobotsFIWARE
 
Building Your Robot using AWS Robomaker
Building Your Robot using AWS RobomakerBuilding Your Robot using AWS Robomaker
Building Your Robot using AWS RobomakerAlex Barbosa Coqueiro
 

Similar to Reactive robotics io_t_2017 (20)

Reactive Java Robotics IoT - jPrime 2016
Reactive Java Robotics IoT - jPrime 2016Reactive Java Robotics IoT - jPrime 2016
Reactive Java Robotics IoT - jPrime 2016
 
Reactive Microservices with Spring 5: WebFlux
Reactive Microservices with Spring 5: WebFlux Reactive Microservices with Spring 5: WebFlux
Reactive Microservices with Spring 5: WebFlux
 
Reactive Java Robotics & IoT with Spring Reactor
Reactive Java Robotics & IoT with Spring ReactorReactive Java Robotics & IoT with Spring Reactor
Reactive Java Robotics & IoT with Spring Reactor
 
IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016IPT High Performance Reactive Java BGOUG 2016
IPT High Performance Reactive Java BGOUG 2016
 
NGRX Apps in Depth
NGRX Apps in DepthNGRX Apps in Depth
NGRX Apps in Depth
 
Microservices with Spring 5 Webflux - jProfessionals
Microservices  with Spring 5 Webflux - jProfessionalsMicroservices  with Spring 5 Webflux - jProfessionals
Microservices with Spring 5 Webflux - jProfessionals
 
Spring 5 Webflux - Advances in Java 2018
Spring 5 Webflux - Advances in Java 2018Spring 5 Webflux - Advances in Java 2018
Spring 5 Webflux - Advances in Java 2018
 
Making Machine Learning Easy with H2O and WebFlux
Making Machine Learning Easy with H2O and WebFluxMaking Machine Learning Easy with H2O and WebFlux
Making Machine Learning Easy with H2O and WebFlux
 
Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9Stream Processing with CompletableFuture and Flow in Java 9
Stream Processing with CompletableFuture and Flow in Java 9
 
fogcomputing
fogcomputingfogcomputing
fogcomputing
 
IT TRENDS AND PERSPECTIVES 2016
IT TRENDS AND PERSPECTIVES 2016IT TRENDS AND PERSPECTIVES 2016
IT TRENDS AND PERSPECTIVES 2016
 
Fog Computing - DEV.BG 2018
Fog Computing - DEV.BG 2018Fog Computing - DEV.BG 2018
Fog Computing - DEV.BG 2018
 
Cytoscape CI Chapter 2
Cytoscape CI Chapter 2Cytoscape CI Chapter 2
Cytoscape CI Chapter 2
 
StrongLoop Overview
StrongLoop OverviewStrongLoop Overview
StrongLoop Overview
 
React Native e IoT - Un progetto complesso
React Native e IoT - Un progetto complessoReact Native e IoT - Un progetto complesso
React Native e IoT - Un progetto complesso
 
Building Robotics Application at Scale using OpenSource from Zero to Hero
Building Robotics Application at Scale using OpenSource from Zero to HeroBuilding Robotics Application at Scale using OpenSource from Zero to Hero
Building Robotics Application at Scale using OpenSource from Zero to Hero
 
N01 cloud computing_and_gae
N01 cloud computing_and_gaeN01 cloud computing_and_gae
N01 cloud computing_and_gae
 
FIWARE Wednesday Webinars - How to Develop FIWARE NGSI Interfaces for Robots
FIWARE Wednesday Webinars - How to Develop FIWARE NGSI Interfaces for RobotsFIWARE Wednesday Webinars - How to Develop FIWARE NGSI Interfaces for Robots
FIWARE Wednesday Webinars - How to Develop FIWARE NGSI Interfaces for Robots
 
Building Your Robot using AWS Robomaker
Building Your Robot using AWS RobomakerBuilding Your Robot using AWS Robomaker
Building Your Robot using AWS Robomaker
 
AF-2599-P.docx
AF-2599-P.docxAF-2599-P.docx
AF-2599-P.docx
 

More from Trayan Iliev

Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorTrayan Iliev
 
IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018Trayan Iliev
 
Learning Programming Using Robots - Sofia University Conference 2018
Learning Programming Using Robots - Sofia University Conference 2018 Learning Programming Using Robots - Sofia University Conference 2018
Learning Programming Using Robots - Sofia University Conference 2018 Trayan Iliev
 
Active Learning Using Connected Things - 2018 (in Bulgarian)
Active Learning Using Connected Things - 2018 (in Bulgarian)Active Learning Using Connected Things - 2018 (in Bulgarian)
Active Learning Using Connected Things - 2018 (in Bulgarian)Trayan Iliev
 
What's new in java 9?
What's new in java 9?What's new in java 9?
What's new in java 9?Trayan Iliev
 
React HOCs, Context and Observables
React HOCs, Context and ObservablesReact HOCs, Context and Observables
React HOCs, Context and ObservablesTrayan Iliev
 
IPT angular2 typescript SPA 2016
IPT angular2 typescript SPA 2016IPT angular2 typescript SPA 2016
IPT angular2 typescript SPA 2016Trayan Iliev
 
New MVC 1.0 JavaEE 8 API
New MVC 1.0 JavaEE 8 APINew MVC 1.0 JavaEE 8 API
New MVC 1.0 JavaEE 8 APITrayan Iliev
 
IPT High Performance Reactive Programming with JAVA 8 and JavaScript
IPT High Performance Reactive Programming with JAVA 8 and JavaScriptIPT High Performance Reactive Programming with JAVA 8 and JavaScript
IPT High Performance Reactive Programming with JAVA 8 and JavaScriptTrayan Iliev
 
IPT Workshops on Java Robotics and IoT
IPT Workshops on Java Robotics and IoTIPT Workshops on Java Robotics and IoT
IPT Workshops on Java Robotics and IoTTrayan Iliev
 
IPT – Java Robotics and IoT
IPT – Java Robotics and IoTIPT – Java Robotics and IoT
IPT – Java Robotics and IoTTrayan Iliev
 
Novelties in Java EE 7: JAX-RS 2.0 + IPT REST HATEOAS Polling Demo @ BGOUG Co...
Novelties in Java EE 7: JAX-RS 2.0 + IPT REST HATEOAS Polling Demo @ BGOUG Co...Novelties in Java EE 7: JAX-RS 2.0 + IPT REST HATEOAS Polling Demo @ BGOUG Co...
Novelties in Java EE 7: JAX-RS 2.0 + IPT REST HATEOAS Polling Demo @ BGOUG Co...Trayan Iliev
 

More from Trayan Iliev (12)

Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and Ktor
 
IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018IPT Reactive Java IoT Demo - BGOUG 2018
IPT Reactive Java IoT Demo - BGOUG 2018
 
Learning Programming Using Robots - Sofia University Conference 2018
Learning Programming Using Robots - Sofia University Conference 2018 Learning Programming Using Robots - Sofia University Conference 2018
Learning Programming Using Robots - Sofia University Conference 2018
 
Active Learning Using Connected Things - 2018 (in Bulgarian)
Active Learning Using Connected Things - 2018 (in Bulgarian)Active Learning Using Connected Things - 2018 (in Bulgarian)
Active Learning Using Connected Things - 2018 (in Bulgarian)
 
What's new in java 9?
What's new in java 9?What's new in java 9?
What's new in java 9?
 
React HOCs, Context and Observables
React HOCs, Context and ObservablesReact HOCs, Context and Observables
React HOCs, Context and Observables
 
IPT angular2 typescript SPA 2016
IPT angular2 typescript SPA 2016IPT angular2 typescript SPA 2016
IPT angular2 typescript SPA 2016
 
New MVC 1.0 JavaEE 8 API
New MVC 1.0 JavaEE 8 APINew MVC 1.0 JavaEE 8 API
New MVC 1.0 JavaEE 8 API
 
IPT High Performance Reactive Programming with JAVA 8 and JavaScript
IPT High Performance Reactive Programming with JAVA 8 and JavaScriptIPT High Performance Reactive Programming with JAVA 8 and JavaScript
IPT High Performance Reactive Programming with JAVA 8 and JavaScript
 
IPT Workshops on Java Robotics and IoT
IPT Workshops on Java Robotics and IoTIPT Workshops on Java Robotics and IoT
IPT Workshops on Java Robotics and IoT
 
IPT – Java Robotics and IoT
IPT – Java Robotics and IoTIPT – Java Robotics and IoT
IPT – Java Robotics and IoT
 
Novelties in Java EE 7: JAX-RS 2.0 + IPT REST HATEOAS Polling Demo @ BGOUG Co...
Novelties in Java EE 7: JAX-RS 2.0 + IPT REST HATEOAS Polling Demo @ BGOUG Co...Novelties in Java EE 7: JAX-RS 2.0 + IPT REST HATEOAS Polling Demo @ BGOUG Co...
Novelties in Java EE 7: JAX-RS 2.0 + IPT REST HATEOAS Polling Demo @ BGOUG Co...
 

Recently uploaded

Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnershipsexpandedwebsite
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxneillewis46
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxLimon Prince
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptxPoojaSen20
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptxVishal Singh
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17Celine George
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...Gary Wood
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppCeline George
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxMarlene Maheu
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint23600690
 
Scopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsScopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsISCOPE Publication
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................MirzaAbrarBaig5
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....Ritu480198
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportDenish Jangid
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽中 央社
 

Recently uploaded (20)

Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
MOOD STABLIZERS DRUGS.pptx
MOOD     STABLIZERS           DRUGS.pptxMOOD     STABLIZERS           DRUGS.pptx
MOOD STABLIZERS DRUGS.pptx
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptx
 
How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17How to Send Pro Forma Invoice to Your Customers in Odoo 17
How to Send Pro Forma Invoice to Your Customers in Odoo 17
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
An Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge AppAn Overview of the Odoo 17 Knowledge App
An Overview of the Odoo 17 Knowledge App
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
Scopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS PublicationsScopus Indexed Journals 2024 - ISCOPUS Publications
Scopus Indexed Journals 2024 - ISCOPUS Publications
 
male presentation...pdf.................
male presentation...pdf.................male presentation...pdf.................
male presentation...pdf.................
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 

Reactive robotics io_t_2017

  • 1. Trayan Iliev tiliev@iproduct.org http://iproduct.org Copyright © 2003-2016 IPT - Intellectual Products & Technologies Multi-agent Systems and Social Robotics 2017 Reactive Robotics & IoT - Introduction
  • 2. 2 Trademarks Oracle®, Java™ and JavaScript™ are trademarks or registered trademarks of Oracle and/or its affiliates. LEGO® is a registered trademark of LEGO® Group. Programs are not affiliated, sponsored or endorsed by LEGO® Education or LEGO® Group. Raspberry Pi™ is a trademark of Raspberry Pi Foundation. Other names may be trademarks of their respective owners.
  • 3. Tales of JAVA Robotics 3 There are several tales to share: Tale of Robotics, IoT and Complexity Tale of Common Sense: DDD Tale of two cities - Imperative and Reactive  Tale of two brave robots: LeJaRo and IPTPI  And some real reactive Java + TypeScript / Angular 2 / WebSocket code 
  • 4. 4 High Performnce Reactive JAVA  Reactive programming. Reactor & Proactor design patterns. Reactive Streams (java.util.concurrent.Flow)  High performance non-blocking asynchronous apps on JVM using Reactor project & RxJava  Disruptor (RingBuffer), Flux & Mono, Processors  End-to-end reactive web applications and services: Reactor IO (REST, WebSocket) + RxJS + Angular 2  Demo - reactive hot event streams processing on Raspberry Pi 2 (ARM v7) based robot IPTPI.  RxJava (not Zen only :) coans for self assessment
  • 5. Where to Find the Demo Code? 5 IPTPI Reactive Demo is available @ GitHub: https://github.com/iproduct/jprime-demo
  • 6. Robots Can Be Complex 6
  • 7. … Even More Complex 7 Cross-section of many disciplines:  mechanical engineering  electrical engineering  computer science  artificial intelligence (AI)  human-computer interaction  sociology & psychology Picture by Hugo Elias of the Shadow Robot Company - http://www.shadowrobot.com/media/pictures.shtml, CC BY-SA 3.0
  • 8. Engineering, Science & Art 8 Source: https://commons.wikimedia.org/w/index.php?curid=551256, CC BY-SA 3.0
  • 9. and How Can We Forget 9 Source: https://commons.wikimedia.org/ w/index.php?curid=234900, CC BY-SA 3.0 Source: Korea Institute of Industrial Technology, http://news.naver.com/main/read.nhn? mode=LSD&mid=sec&sid1=102&oid=020&aid=0000371339
  • 10. Robots: The Most Intelligent Things 10 CC BY 2.0, Source: https://www.flickr.com/photos/wilgengebroed/8249565455/ Radar, GPS, lidar for navigation and obstacle avoidance ( 2007 DARPA Urban Challenge )
  • 11. The Internet of Things has the potential to change the world, just as the Internet did. Maybe even more so.  Nearly 50 petabytes of data are captured and created by human beings  People have limited time, attention and accuracy  Capturing data about things in the real world in real time  Track and count everything, reduce waste, loss & cost.  Know when things need replacing, repairing or recalling — Kevin Ashton, 'That 'Internet of Things' Thing', RFID Journal, 2009 Internet of Things (IoT)
  • 12.  There will be nearly 26 billion devices on the Internet of Things by 2020. [Gartner]  More than 30 billion devices will be wirelessly connected to the Internet of Things by 2020 [ABI Research]  It's expected to be a 19 Trillion USD market [John Chambers, Cisco CEO] IoT Perspectives
  • 13. "Basket of remotes" problem – we'll have hundreds of applications to interface with hundreds of devices that don't share protocols for speaking with one another [Jean-Louis Gassée, Apple initial team, and BeOS co-founder] Only IPv6 addresses are not enough – IoT devices should be also easily and directly accessible for users and [their] agents In read/write mode Preferably using a standard web browser Even behind firewalls IoT - Need for Standards
  • 14. IoT Services Architecture 14 Devices: Hardware + Embedded Software + Firmware UART/ I2C/ 2G/ 3G/ LTE/ ZigBee/ 6LowPan/ BLE Aggregation/ Bus: ESB, Message Broker Device Gateway: Local Coordination and Event Aggregation M2M: HTTP(/2) / WS / MQTT / CoAP Management: TR-069 / OMA-DM / OMA LWM2M HTTP, AMQP Cloud (Micro)Service Mng. Docker, Kubernetes/ Apache Brooklyn Web/ Mobile Portal PaaSDashboard PaaS API: Event Processing Services, Analytics
  • 15. Tracking Complexity 15 We need tools to cope with all that complexity inherent in robotics and IoT domains. Simple solutions are needed – cope with problems through divide and concur on different levels of abstraction: Domain Driven Design (DDD) – back to basics: domain objects, data and logic. Described by Eric Evans in his book: Domain Driven Design: Tackling Complexity in the Heart of Software, 2004
  • 16. Common Sense: DDD 16 Actually DDD require additional efforts (as most other divide and concur modeling approaches :)  Ubiquitous language and Bounded Contexts  DDD Application Layers: Infrastructure, Domain, Application, Presentation  Hexagonal architecture : OUTSIDE <-> transformer <-> ( application <-> domain ) [A. Cockburn]
  • 17. Common Sense: DDD 17 Main concepts:  Entities, value objects and modules  Aggregates and Aggregate Roots [Haywood]: value < entity < aggregate < module < BC  Repositories, Factories and Services: application services <-> domain services  Separating interface from implementation
  • 18. Imperative and Reactive 18 We live in a Connected Universe ... there is hypothesis that all the things in the Universe are intimately connected, and you can not change a bit without changing all. Action – Reaction principle is the essence of how Universe behaves.
  • 19. Imperative and Reactive  Reactive Programming: using static or dynamic data flows and propagation of change Example: a := b + c  Functional Programming: evaluation of mathematical functions, ➢ Avoids changing-state and mutable data, declarative programming ➢ Side effects free => much easier to understand and predict the program behavior. Example: books.stream().filter(book -> book.getYear() > 2010) .forEach( System.out::println )
  • 20. Functional Reactive (FRP) 20 According to Connal Elliot's (ground-breaking paper @ Conference on Functional Programming, 1997), FRP is: (a) Denotative (b) Temporally continuous
  • 22. Reactive Programming 22  Microsoft® opens source polyglot project ReactiveX (Reactive Extensions) [http://reactivex.io]: Rx = Observables + LINQ + Schedulers :) Java: RxJava, JavaScript: RxJS, C#: Rx.NET, Scala: RxScala, Clojure: RxClojure, C++: RxCpp, Ruby: Rx.rb, Python: RxPY, Groovy: RxGroovy, JRuby: RxJRuby, Kotlin: RxKotlin ...  Reactive Streams Specification [http://www.reactive-streams.org/] used by:  (Spring) Project Reactor [http://projectreactor.io/]  Actor Model – Akka (Java, Scala) [http://akka.io/]
  • 23. Trayan Iliev IPT – Intellectual Products & Technologies Ltd. Multi-Agent Systems & Social Robotics 15/01/2015 Slide 23Copyright © 2003-2015 IPT – Intellectual Products & Technologies Ltd. All rights reserved. Подход на интелигентните агенти при моделиране на знания и системи
  • 24. Reactive Streams Spec. 24  Reactive Streams – provides standard for asynchronous stream processing with non-blocking back pressure.  Minimal set of interfaces, methods and protocols for asynchronous data streams  April 30, 2015: has been released version 1.0.0 of Reactive Streams for the JVM (Java API, Specification, TCK and implementation examples)  Java 9: java.util.concurrent.Flow
  • 25. Reactive Streams Spec. 25  Publisher – provider of potentially unbounded number of sequenced elements, according to Subscriber(s) demand. Publisher.subscribe(Subscriber) => onSubscribe onNext* (onError | onComplete)?  Subscriber – calls Subscription.request(long) to receive notifications  Subscription – one-to-one Subscriber ↔ Publisher, request data and cancel demand (allow cleanup).  Processor = Subscriber + Publisher
  • 26. FRP = Async Data Streams 26  FRP is asynchronous data-flow programming using the building blocks of functional programming (e.g. map, reduce, filter) and explicitly modeling time  Used for GUIs, robotics, and music. Example (RxJava): Observable.from(new String[]{"Reactive", "Extensions", "Java"}) .take(2).map(s -> s + " : on " + new Date()) .subscribe(s -> System.out.println(s)); Result: Reactive : on Wed Jun 17 21:54:02 GMT+02:00 2015 Extensions : on Wed Jun 17 21:54:02 GMT+02:00 2015
  • 27. 27  Performance is about 2 things (Martin Thompson – http://www.infoq.com/articles/low-latency-vp ): – Throughput – units per second, and – Latency – response time  Real-time – time constraint from input to response regardless of system load.  Hard real-time system if this constraint is not honored then a total system failure can occur.  Soft real-time system – low latency response with little deviation in response time  100 nano-seconds to 100 milli-seconds. [Peter Lawrey] What About High Performance?
  • 28. 28  Mechanical Sympathy – hardware (CPU, cache, memory, IO, Network), operating system, language implementation platform (e.g. JVM), and application level code are working in harmony to minimize the time needed for event (request, message) processing => 10% / 90% principle  Throughput vs. latency – bus vs. car traveling  Throughput ~ System Capacity / Latency  Achieving low latency may mean additional work done by system => lowered System Capacity and Throughput  Horizontal scalability is valuable for high throughput. For low latency, you need simplicity – critical path. Throughput vs. Latency
  • 29. 29  JVMs can be faster than custom C++ code because of the holistic optimizations that they can apply across an application [Andy Piper].  Developers can take advantage of hardware guarantees through a detailed understanding of: – Java Memory Model & mapping to underlying hardware – low latency software system hardware (CPU, cache, memory, IO, Network) – avoiding lock-contention and garbage collection – Compre-And-Swap – CAS (java.util.concurrent.atomic) – lock-free, wait-free techniques – using standard libraries (e.g. the LMAX Disruptor) High Performance Java
  • 30. 30 CPU Cache – False Sharing Core 2 Core NCore 1 ... Registers Execution Units L1 Cache A | | B | L2 Cache A | | B | L3 Cache A | | B | DRAM Memory A | | B | Registers Execution Units L1 Cache A | | B | L2 Cache A | | B |
  • 31. 31  Low garbage by reusing existing objects + infrequent GC when application not busy – can improve app 2 - 5x  JVM generational GC startegy – ideal for objects living very shortly (garbage collected next minor sweep) or be immortal  Non-blocking, lockless coding or CAS  Critical data structures – direct memory access using DirectByteBuffers or Unsafe => predictable memory layout and cache misses avoidance  Busy waiting – giving the CPU to OS kernel slows program 2-5x => avoid context switches  Amortize the effect of expensive IO - blocking Low Latency: Things to Remember
  • 32. 32  Parallel tasks can increase your throughput by increasing system capacity – it is GOOD!  But comes together with concurrent access to shared resources => you have to provide mutual exclusion (MutEx) by parallel threads when changing the resources' state (read only access can be shared by multiple threads)  Mutual exclusion can be achieved in several ways: – synchronized – hardwired in HotSpot JVM, optimized in J^6 – ReentrantLock, ReadWriteLock, StampedLock → java.util.concurrent.locks.* – Optimistic Locking → tryLock(), CAS Parallelism & Concurrency
  • 33. 33 Simple problem: incrementing a long value 500 000 000 times. 9 implementations: ‒ SynchronousCounter – while (counter++ < 500000000){} ‒ SingleThreadSynchronizedCounter – 1T using synchronized ‒ TwoThreadsSynchronizedCounter – 2T using synchronized ‒ SingleThreadCASCounter – 1T using AtomicLong ‒ TwoThreadsCASCounter – 2T using AtomicLong ‒ TwoThreadsCASCounterLongAdder – 1T using LongAdder ‒ SingleThreadVolatileCounter – 1T, memory barrier (volatile) ‒ TwoThreadsVolatileCounter – 2T, memory barrier (volatile) Comparing Concurrent Impl.
  • 34. 34 Test results (on my laptop - quad core Intel i7@2.2GHz): − SynchronousCounter – 190ms − SingleThreadSynchronizedCounter – 15000 ms − TwoThreadsSynchronizedCounter – 21000 ms − SingleThreadCASCounter – 4100 ms − TwoThreadsCASCounter – 12000 ms − TwoThreadsCASCounterLongAdder – 12800 ms − SingleThreadVolatileCounter – 4100 ms − TwoThreadsVolatileCounter – 20000 ms Comparing Concurrent Impl.
  • 35. 35 For more complete micro-benchmarking of different Mutex implementations see: http://blog.takipi.com/java-8-stampedlocks-vs- readwritelocks-and-synchronized/ http://www.slideshare.net/haimyadid/java-8- stamped-lock Comparing Concurrent Impl.
  • 36. 36  Non-blocking (synchronous) implementation is 2 orders of magnitude better then synchronized  We should try to avoid blocking and especially contended blocking if want to achieve low latency  If blocking is a must we have to prefer CAS and optimistic concurrency over blocking (but have in mind it always depends on concurrent problem at hand and how much contention do we experience – test early, test often, microbenchmarks are unreliable and highly platform dependent – test real application with typical load patterns)  The real question is: HOW is is possible to build concurrency without blocking? Mutex Comparison => Conclusions
  • 37. 37  Message Driven – asynchronous message-passing allows to establish a boundary between components that ensures loose coupling, isolation, location transparency, and provides the means to delegate errors as messages [Reactive Manifesto].  The main idea is to separate concurrent producer and consumer workers by using message queues.  Message queues can be unbounded or bounded (limited max number of messages)  Unbounded message queues can present memory allocation problem in case the producers outrun the consumers for a long period → OutOfMemoryError Scalable, Massively Concurrent
  • 38. 38  Queues typically use either linked-lists or arrays for the underlying storage of elements. Linked lists are not „mechanically sympathetic” – there is no predictable caching “stride” (should be less than 2048 bytes in each direction).  Bounded queues often experience write contention on head, tail, and size variables. Even if head and tail separated using CAS, they usually are in the same cache- line.  Queues produce much garbage.  Typical queues conflate a number of different concerns – producer and consumer synchronization and data storage Queues Disadvantages [http://lmax-exchange.github.com/disruptor/files/Disruptor-1.0.pdf]
  • 39. 39  LMAX Disruptor design pattern separates different concerns in a “mechanically sympathetic” way: - Storage of items being exchanged - Producer coordination – claiming the next sequence - Consumers coordination – notified new item is available  Single Writer principle is employed when writing data in the Ring Buffer from single producer thread only (no contention),  When multiple producers → CAS  Memory pre-allocated – predictable stride, no garbage LMAX Disruptor (RingBuffer) [http://lmax-exchange.github.com/disruptor/files/Disruptor-1.0.pdf]
  • 40. 40 LMAX Disruptor (RingBuffer) High Performance [http://lmax-exchange.github.com/disruptor/files/Disruptor- 1.0.pdf] Source: LMAX Disruptor github wiki - https://raw.githubusercontent.com/wiki/LMAX- Exchange/disruptor/images/Models.png LMAX-Exchange Disruptor License @ GitHub: Apache License Version 2.0, January 2004 - http://www.apache.org/licenses/
  • 41. 41 LMAX Disruptor (RingBuffer) High Performance [http://lmax-exchange.github.com/disruptor/files/Disruptor- 1.0.pdf] Source: LMAX Disruptor @ GitHub - https://github.com/LMAX- Exchange/disruptor/blob/master/docs/Disruptor.docx LMAX-Exchange Disruptor License @ GitHub: Apache License Version 2.0, January 2004 - http://www.apache.org/licenses/
  • 42. Project Reactor 42  Reactor project allows building high-performance (low latency high throughput) non-blocking asynchronous applications on JVM.  Reactor is designed to be extraordinarily fast and can sustain throughput rates on order of 10's of millions of operations per second.  Reactor has powerful API for declaring data transformations and functional composition.  Makes use of the concept of Mechanical Sympathy built on top of Disruptor / RingBuffer.
  • 43. Project Reactor 43  Pre-allocation at startup-time  Message-passing structures are bounded  Using Reactive and Event-Driven Architecture patterns => non-blocking end-to-end flows, replies  Implement Reactive Streams Specification – efficient bounded structures requesting no more than capacity  Applies above features to IPC and provides non- blocking IO drivers that are flow-control aware  Expose a Functional API – organize their code in a side-effect free way, which helps you determine you are thread-safe and fault-tolerant
  • 44. Reactor Projects 44 https://github.com/reactor/reactor, Apache Software License 2.0 IPC – Netty, Kafka, Aeron
  • 49. Reactor: Hello World 49 public static void main(String... args) throws InterruptedException { EmitterProcessor<String> emitter = EmitterProcessor.create(); BlockingSink<String> sink = emitter.connectSink(); emitter.publishOn(Schedulers.single()) .map(String::toUpperCase) .filter(s → s.startsWith("HELLO")) .delayMillis(1000).subscribe(System.out::println); sink.submit("Hello World!"); // emit - non blocking sink.submit("Goodbye World!"); sink.submit("Hello Trayan!"); Thread.sleep(3000); }
  • 50. Reactor: Flux Example 50 Flux.fromIterable(getSomeLongList()) .mergeWith(Flux.interval(100)) .doOnNext(serviceA::someObserver) .map(d -> d * 2) .take(3) .onErrorResumeWith(errorHandler::fallback) .doAfterTerminate(serviceM::incrementTerminate) .subscribe(System.out::println); https://github.com/reactor/reactor-core, Apache Software License 2.0
  • 51. Reactor Bus: IPTPI Java Robot 51
  • 52. Disruptor (Ring Buffer) used in Reactor 52 Reactor provides 3 major types of Processors:  EmitterProcessor – using 0 threads (on same thread)  TopicProcessor using – N threads concurrently processing the messages (AND operation)  WorkQueueProcessor – N threads alternatively processing the messages (XOR operation – messages are processed exactly by one thread – load ballancing and work distribution)
  • 55. IPTPI: RPi2 + Ardunio Robot 55  Raspberry Pi 2 (quad-core ARMv7 @ 900MHz) + Arduino Leonardo cloneA-Star 32U4 Micro  Optical encoders (custom), IR optical array, 3D accelerometers, gyros, and compass MinIMU-9 v2  IPTPI is programmed in Java using Pi4J, Reactor, RxJava, Akka  More information about IPTPI: http://robolearn.org/iptpi-robot/
  • 56. IPTPI: RPi2 + Ardunio Robot 56 3D accelerometers, gyros, and compass MinIMU-9 v2 Pololu DRV8835 Dual Motor Driver for Raspberry Pi Arduino Leonardo clone A-Star 32U4 Micro USB Stereo Speakers - 5V LiPo Powebank 15000 mAh
  • 57. IPTPI: RPi2 + Ardunio Robot 57 Raspberry Pi 2 (quad-core ARMv7 @ 900MHz) IR Optical Sensor QRD1114 Array (Line Following) Adafruit 2.8" PiTFT - Capacitive Touch Screen
  • 58. 58
  • 59. LeJaRo: Lego® Java Robot 59  Modular – 3 motors (with encoders) – one driving each track, and third for robot clamp.  Three sensors: touch sensor (obstacle avoidance), light color sensor (follow line), IR sensor (remote).  LeJaRo is programmed in Java using LeJOS library.  More information about LeJaRo: http://robolearn.org/lejaro/  Programming examples available @GitHub: https://github.com/iproduct/course-social-robotics/tre e/master/motors_demo LEGO® is a registered trademark of LEGO® Group. Programs of IPT are not affiliated, sponsored or endorsed by LEGO® Education or LEGO® Group.
  • 62. IPTPI: IPTPIDemo I 62 public class IPTPIVDemo { ... public IPTPIDemo() { //receive Arduino data readings ArduinoData = ArduinoFactory.getInstance().createArduinoData(); //calculate robot positions PositionsFlux = PositionFactory.createPositionFlux( arduinoData.getEncoderReadingsFlux()); resentationViews.add( PositionFactory.createPositionPanel(positionsFlux)); //enable sending commands to Arduino ArduinoCommandsSub = ArduinoFactory.getInstance() .createArduinoCommandSubscriber(); /
  • 63. IPTPI: IPTPIDemo II 63 //Audio player - added @jPrime 2016 Hackergarten audio = AudioFactory.createAudioPlayer(); //wire robot main controller with services movementSub =MovementFactory.createMovementCommandSubscriber( positionsFlux, arduinoData.getLineReadingsFlux()); controller = new RobotController(this::tearDown, movementSub, arduinoCommandsSub, audio); //create view with controller and delegate material views from query services view = new RobotView("IPTPI Reactive Robotics Demo", controller, presentationViews);
  • 64. IPTPI: IPTPIDemo III 64 //expose as WS service movementSub2 =MovementFactory.createMovementCommandSubscriber( positionsFlux, arduinoData.getLineReadingsFlux()); positionsService = new RobotWSService( positionsFlux, movementSub2); } public static void main(String[] args) { // initialize wiringPi library Gpio.wiringPiSetupGpio(); try { IPTPIDemo demo = new IPTPIDemo(); } catch (IOException e) { e.printStackTrace(); } }
  • 65. IPTPI: ArduinoData I 65 positionsFlux = EmitterProcessor.create(); positionsSink = positionsFlux.connectSink(); lineFlux = EmitterProcessor.create(); lineSink = lineFlux.connectSink(); final Serial serial = SerialFactory.createInstance(); serial.addListener(new SerialDataEventListener() { private ByteBuffer buffer = ByteBuffer.allocate(1024); public void dataReceived(SerialDataEvent event) { try { ByteBuffer newBuffer = event.getByteBuffer(); buffer.put(newBuffer); buffer.flip(); ... buffer.get(); long timestamp = buffer.getInt(); //get timestamp int encoderL = -buffer.getInt(); //motors mirrored int encoderR = buffer.getInt();
  • 66. IPTPI: ArduinoData II 66 EncoderReadings readings = new EncoderReadings(encoderR, encoderL, timestamp); emitter.submit(readings); ... buffer.compact(); } catch (Exception e) { e.printStackTrace(); } } }); try { serial.open(PORT, 38400); } catch(SerialPortException | IOException ex) { System.out.println(“SERIAL SETUP FAILED:"+ex.getMessage()); }
  • 67. IPTPI: PositionFlux I 67 Redux Pattern! public PositionsFlux( Flux<EncoderReadings> readingsFlux) { this.encoderReadings = readingsFlux; Flux<EncoderReadings> skip1 = readingsFlux.skip(1); positionsFlux = Flux.zip(readingsFlux, skip1) .map(tupple -> .scan(new Position(0, 0, 0), (last, tupple) -> { EncoderReadings prev = tupple.getT1(); EncoderReadings curr = tupple.getT2(); int prevL = prev.getEncoderL(); int prevR = prev.getEncoderR(); int currL = curr.getEncoderL(); int currR = curr.getEncoderR(); int sL = currL - prevL; int sR = currR - prevR; double alpha0 = last.getHeading();
  • 68. IPTPI: PositionFlux II 68 double alpha0 = last.getHeading(); if(sR == sL) { return new Position((float)(last.getX() + sL * ENCODER_STEP_LENGTH * cos(alpha0)), (float)(last.getY()+ sL * ENCODER_STEP_LENGTH * sin(alpha0)), alpha0, curr.getTimestamp()); } else { … } }) ); }
  • 69. CommandMovementSubscriber I 69 public class CommandMovementSubscriber extends ConsumerSubscriber<Command<Movement>> { private PositionFluxion positions; public CommandMovementSubscriber(PositionFluxion positions){ this.positions = positions; Gpio.wiringPiSetupGpio(); // initialize wiringPi library Gpio.pinMode(5, Gpio.OUTPUT); // Motor direction pins Gpio.pinMode(6, Gpio.OUTPUT); Gpio.pinMode(12, Gpio.PWM_OUTPUT); // Motor speed pins Gpio.pinMode(13, Gpio.PWM_OUTPUT); Gpio.pwmSetMode(Gpio.PWM_MODE_MS); Gpio.pwmSetRange(MAX_SPEED); Gpio.pwmSetClock(CLOCK_DIVISOR); } @Override public void doNext(Command<Movement> command) { ... } }
  • 70. CommandMovementSubscriber II 70 private void runMotors(MotorsCommand mc) { //setting motor directions Gpio.digitalWrite(5, mc.getDirR() > 0 ? 1 : 0); Gpio.digitalWrite(6, mc.getDirL() > 0 ? 1 : 0); //setting speed if(mc.getVelocityR()>=0 && mc.getVelocityR() <=MAX_SPEED) Gpio.pwmWrite(12, mc.getVelocityR()); // set speed if(mc.getVelocityL()>=0 && mc.getVelocityL() <=MAX_SPEED) Gpio.pwmWrite(13, mc.getVelocityL()); } }
  • 71. Reactor IO – NetStreams API 71 http://projectreactor.io/io/docs/reference/, Apache License 2.0
  • 72. Takeaways: Why Go Reactive? 72 Benefits using Reactive Programming + DDD:  DDD helps to manage complexity in IoT and Robotics - many subsystems = sub-domains  Reactive Streams (Fluxes, Monos) = uni-directional data flows, CQRS, event sourcing, microservices  Reactive Streams can be non-blocking and highly efficient, or can utilize blocking if needed  Naturally implement state management patterns like Redux, allow time travel, replay and data analytics  Clear, declarative data transforms that scale (Map- Reduce, BigData, PaaS)
  • 73. Takeaways: Why Maybe Not? 73 Cons using Reactive Programming + DDD:  DDD requires additional efforts to clearly separate different (sub) domains – DSL translators, factories...  Reactive Streams utilize functional composition and require entirely different mindset then imperative – feels like learning foreign language  Pure functions and Redux provide much benefits, but there's always temptation to “do it the old way” :)  Tool support for functional programming in Java is still not perfect (in Eclipse at least :)
  • 74. Where to Find the Demo Code? 74 IPTPI Reactive Demo is available @ GitHub: https://github.com/iproduct/jprime-demo
  • 75. 75 Resources: RxMarbles & Rx Coans RxMarbles: http://rxmarbles.com/ RxJava Koans – Let's try to solve them at: https://github.com/mutexkid/rxjava-koans RxJS Koans – for those who prefer JavaScript :) https://github.com/Reactive-Extensions/RxJSKoans
  • 76. Tale of Simplicity: DDD 76 http://robolearn.org/ Let's move! http://iproduct.org/
  • 77. Thank’s for Your Attention! 77 Trayan Iliev CEO of IPT – Intellectual Products & Technologies http://iproduct.org/ http://robolearn.org/ https://github.com/iproduct https://twitter.com/trayaniliev https://www.facebook.com/IPT.EACAD https://plus.google.com/+IproductOrg