 Hey everybody, I'm Josh Adams and I'm slated to give this talk, the intro to Elixir's Ruby. I gave this at a Ruby conference and I liked it. It's very introductory. So we just gave a talk at Oskon on distributed robots with Elixir. And so Jim was okay with us giving basically both talks in this time frame. So I'm going to kind of speed through the intro because I feel like, I'm going to try to cover it pretty rapidly and then move on to the other one because there's some more fun, robots are fun. Anyway, so the goal of this is to explain to Ruby is to want to give Elixir a shot. I think everybody here has already decided probably to give Elixir a shot. So it focuses on showing the syntax and the primitives of the language and comparing them to Ruby where it comes from. So yeah, sorry, my name is Hugh Jose. He started this when he took a sabbatical from Rails 4. Yeah, okay. And yeah, so Elixir is awesome. And it's built on top of the early virtual machine, everyone lives in this. So I have all those physical shots. My brother-in-law found some tanks with Elixir on the side of them. Alright, so the official Elixir sales pitch I think everyone knows. It's fault-tolerant metaprogramming where functional. We're good. Dave Thomas, again, we all know that he likes Elixir. I don't need to cover that part. The issue, so I write a lot of Ruby, and the issue is when you're trying to do concurrent stuff, there's all this mutable state. And this is about the most mutable state. And it ends up making things complicated. I built a thing in Somuloid. There's this distributed system. It had a lot of Bitcoin trading platform. And it was incredibly frustrating not because of Somuloid. But because all the Ruby libraries deal with mutable state pretty poorly. And the killer problem I had, the worst problem I had was RSpec's mocks. There were situations that they're just now still trying to get over where RSpec mocks are not thread safe since the RSpec 3 transition. And that killed me. I was very deep into this project and then all of a sudden my test suite had weird failures. And you don't want your test suite to be causing you problems. Anyway, so that was honestly the sort of thing that made me start thinking, I probably want to look into getting into the active model more natively. Not in Ruby, but in Erlang. So I looked at Erlang for a bit and then moved on to Elixir. So Devin Torres, he's very, very well known in Erlang. And he said this, I thought it was great. So anyway. And then this last year, a year and a half ago at RubyConf, Matt said he is not a threading guy and this thing came out. So that was unpleasant. But mostly true, right? Ruby is not terribly good at threads. Not Ruby the language, but Ruby the library ecosystem. Ruby the language is getting much better at threads. But it doesn't matter if you want it, like one of the big benefits of Ruby is it's got all these libraries, but if you can't use them, that benefit goes away. Anyway, so that's the pitch for Elixir. So why am I qualified to talk about it? Okay, so I'm the CTO of IceTip11. We're a software consultancy. We've been doing Ruby. We've done a lot of distributed stuff. We're over eight years old. We're very comfortable with JavaScript, Erlang, all that stuff. And we're looking for new developers, just as a side note. Also I run a subscription screencast series called ElixirSips. It chronicles my journey from the beginning through now of learning Elixir. There's like 11 hours of video and 95 of them, I think. And it's pretty awesome. It also helps me eat. So anyway, I've written a lot of Elixir code as a consequence of both, well, mostly ElixirSips, and we're doing a little bit of production Elixir now. Okay. So on to the actual talk. So very basic Elixir. We're going to cover data types, pattern matching, functions, modules, and mix. So core data types, atoms, number strings, lists, tuples, maps, regex, booleans. Atoms are just like symbols in Ruby. They're a colon followed by letters, digits, and underscores, and you might use them to tag tuples. It's very common to see just an atom at the front of a tuple, and that explains what type of a bit of data this is. Strings are just like strings in Ruby, except for they are on objects, and they also handle Unicode better than Ruby. Although Ruby's got a little bit better, Elixir's still better. And if you want to see really cool metaprogramming, look at how Elixir builds out its Unicode support from the Unicode data.txt code point file. It's very neat. Integers can be written in various ways. So if you're coming from Ruby, you can still use your underscores so that your numbers are readable. Floating points, there, numbers with a decimal point, nothing really big there, right? Also, just like Ruby though, you have to have a zero in front of them for it to know that it's floating point. Lists look like arrays in other languages, although they're not arrays. They have different semantics. So writing a list is easy. You just put stuff in, square brackets. Due to the way they're implemented, the easiest thing to do is get the tail and the head, and that's because they're actually linked lists behind the scenes. And you can use the HD and TL functions to access the head and the tail, and that pretty much covers it right. Tuples, they're just ordered collections, curly braces, surrounding items separated by columns. Use them in pattern matching very commonly, and as return values from various functions, and those two facts aren't unrelated, right, because you want to pattern match on your return value. And tuples are actually contiguous areas of memory behind the scenes, and so they can be accessed in constant time rather than lists. Okay, so maps, they're like hashes for the most part. They're very new in Erlang. They landed in R17, and so as of this writing, they are actually still slow for large numbers of keys. At Erlang factory, they said that that was going to be fixed in 17.1, but then there were crickets, so I'm assuming that's going to be fixed soon. Anyway, so since Elixir is just a citizen of Erlang's VM, and these are a large number of keys, it's unusual to have hash with that many keys unless you're like building cash or something, right? Anyway, but once Erlang gets them, Elixir will get them. Updating a map has interesting behavior, so the syntax is interesting. First off, you've got this pipe thing that doesn't look anything like a ruby thing, and that's obviously because these are immutable things. You're not actually modifying a map. You're returning a new one. Also, if you attempt to update a non-existent key, it's going to result in an argument error. So we took over a ruby and Mongo project from a Fortune 500 company that had another programming team write this big data migration tool, and they have many, many tens and hundreds of thousands of pages on their site, and it's a very Mongo-esque CMS, right? So if this key exists, show a photo gallery, as an example. And so all these documents, just the templates would figure out how to show the document based on where it was in the hierarchy and what keys it had. The developer typoed the word gallery. There was only one L. So three months after they launched their big rewrite, they realized they had, I don't know, 5,000 photo gallery pages that had no photos on them. So this would be really nice there, right? You can't accidentally do that. I see that as a benefit, an actual, like, money-saving benefit for businesses. Anyway, so that was very happy for me. Elixir has pro-compatible regular expressions, so you can use them just like all the regexes you're used to. Use the R sigil to build a regex. Ruby uses sigils. I'm glad to see them in Elixir. And a lot of the more advanced use cases for regexes are supported, like name captures and scan. I would really like the way name captures work. In Elixir, everything but false or nil is truthy, and false and nil are both short ends for atoms with the same name. So they're just the same thing as the atom false or the atom nil. And so that's it for the basics, right? That's all the basic syntax for the most part are data types. So now we'll have a look at places you might make use of pattern matching. So we'll see the match operator, function definitions, and case statements. So the match operator is just the equal sign. It looks like variable assignment, but it's not. So here this sets the unbound variable foo. Very normal looking. So that would freak you out if you were a Ruby developer. So it's not assignment. It's matching, right? So basically you're making an assertion. You're saying if you assert something about an unbound variable or in Elixir a bound variable, Elixir will bind the variable and the assertion will pass. So foo already had the value one. And so this match will, sorry, here, foo already had the value one. So the match fails, match error is thrown. And you're going to run in a match error a lot. You want it. You want it to catch when you expected, for instance, a good HTTP request and you didn't get one. Okay, so let's look at some more advanced matches just to further explore how what we're doing is something entirely different from assignment. So this, anybody know what this does? Anyone new to Elixir know what this does? It just binds the variable bar to the value three, right? So, yeah, underscores play an interesting role. They basically say, I don't care about this value, right? So here we're binding Baz, too, and we don't care about the first value. They're like a wild card for pattern matching. So imagine that we knew that the value we were interested in and the data structure we were matching was in its second position and we didn't care about the other components. That's basically all we're saying here. There's one more important point in Elixir that's different from Erlang and it confused me in my first probably three weeks of dealing with it. And that's if you want to use a variable in a pattern match to filter something. In Erlang, there's only like single assignment, right? So you can't assign a variable twice. In Elixir, that's gone, but you can still get the single assignment semantics. So that bottom one with the hat, that says, A has the value that I want to filter here. And so don't rebind A. Just use whatever's in that variable. Anyway, so that's nice. I used that a bit in Erlang and it was... Yes, that's a carrot. Yes, that's a carrot. It's a hat or whatever. Yes. Anyway, and so that's just the way that Elixir differentiates between variable binding and using variables, existing values for matches. So it's a decent trade-off. I definitely like not seeing programs that have value one, value two, value three, value four, which is what you'll run into in Erlang because there's single assignment. And then you'll realize, oh, this guy forgot to pass in value four. He had value three there, so there's a bug because he just forgot to increment a number. Like that's not the bugs I want in my code. I don't think it's very common in stuff you see out in the wild in Erlang, but I've certainly done it. Anyway, pattern matching is used to choose between multiple possible definitions of a function. As an example, here's a silly function. It just prints very nice things about me and doesn't care about anyone else. So, again, this function is defined differently depending on the pattern that its arguments match. So this is the first really intensely different sort of thing that I ran into in Elixir or Erlang. I was a math major in college. When I first ran across this thing in Erlang, it made me really excited because if you ever see how, like, functions in math are defined, they'll say, you know, for the zero case it does this, for the one case it does this, and obviously recursive functions might fall back to the zero case eventually. It just felt really nice and that's how I like to see functions defined. Case statements can be used for control flow and they also operate on pattern matching. So here you can see the middle case is what's going to match. The second one, the first one doesn't match at all. The second one matches, and the third one would match because the underscore matches anything, but since they're handled from the top to the bottom, it's not going to get hit. So that's it for just the basics of pattern matching and we'll move on to functions. The other functions are first-class types. This isn't surprising, right? It's a functional programming language. So let's look at defining anonymous functions, calling them and then using them as first-class types. Anonymous functions are defined with the FN keyword. So this is what that looks like. I think we basically just saw something very similar. They take parameter lists and bodies and those are separated by arrows. The parameter lists are used for pattern matching and we saw this just a second ago. So here the print name function will match a tuple containing three elements when the first element is the atom person and then it matches to a body that concatenates the second, third elements together, which we know are the first and last names. The syntax to call an anonymous function elixir is a little weird. There you go. So you have to call it with a dot, so it's not like calling it with a function from a module. It does make calling them feel different from calling functions and modules so what happens if you call it with an argument that doesn't match any of the parameter lists? Right, so we get a function clause error. Basically, there's no function defined that handles the input. So there was a discussion about removing the dot to call anonymous functions. I guess Jose will know whether that's going to go anywhere. So let's define an anonymous function that behaves differently depending on the arguments provided to it. So here we've got anonymous function. If you give it a list of two items, it returns the sum of their prices. If you give it a single item, it just returns the price. This is a silly way to define the sort of function. You might want to recurse across the list, but recursion on anonymous functions is actually way easier now, but it was hard when I wrote this. So anyway, so you can call this function with either a single item or a list containing two items and it returns the price. Anyway, like I said, it's silly, but it works and it's a fairly decent example to define functions for different cases. Since functions are first class in Elixir, you can pass them as arguments or you can return them from other functions. So let's play with that. Here, add is a function that takes an argument and returns a function that will add that argument to the new function's single argument. So we can use that to generate a function that adds three to whatever argument you give it. You can also write functions that take other functions as arguments. So here's an example. Basically, we have greet person, and then it just calls the greeter on the person table. It's not a very brilliant function, right? But you can see how it works and that you can, in fact, pass in functions as arguments to other functions. So modules are the primary unit of code organization in Elixir. So they can contain functions private and public. And so real quick, we'll cover using mix to begin a new project, defining a module, compiling one, the fact that they have return values, which is awesome, documenting them and then generating your documentation output. So mix is used for creating, compiling and testing Elixir projects. And so you can just call mix new. It generates a bunch of files for you. It generates this mix.exe that's kind of collapsed a little bit. And so here you can you can put your dependencies in here. Now there is hex, which is the package manager for Elixir. So you would expect mostly to not have get dependencies in there as soon as possible. Anyway, so this is just your basic mix file. Here's a trivial example of defining a module with a single function, just so you see it. It's very easy. Just returns the argument. So you can launch IEX. You can give it the EX file as an example and then you can call that modules functions. You can also use Elixir C to compile it. And so if you do that, it'll generate a beam file and then you can call IEX and by default, it'll pull all the beam files from the directory it's launched from. You can also pass it arguments that tell it hey, fine, beam files here and here and here. And beam is the Erlang virtual machine and it's, you know, Erlang modules compile down to beam files just the same way that Elixir modules do. I'm going to skip a little bit here. Def module has a return value. It's pretty great. Makes has help built in so you can define documentation in your modules. And yeah, so there's list comprehension, structs, the pipe operator, recursion, processes, agents and tasks. So this is sort of the rest of the talk and we'll go through it. So list comprehension are a syntax for mapping, filtering and combining all in one. So this is what they look like. So for X in this list do X times 2 and it'll return a new list. In the second example, you can see that I'm returning a new list with two elements. And in the third example I'm filtering out things that are not even. So it's pretty nice. But you can combine lists too. So here we're saying for all the X and 1, 2 and 3 and the Y and 4, 5 and 6, go ahead and show me their multiples. And so you get back a list that is all of that, which is nice. It combines it across all of them. So it gets more interesting. Maybe you want to generate a list of tuples showing all the combinations of these two lists. So that's pretty nice. You can also get fancy and do crazy things. So here all the numbers based on the first five odd numbers and the first five even numbers where the product minus 1 is divisible by 9, which is very normal. Anyway, that's a very terse way to write that. I like it quite a bit. So it's a contrived example, but it's fairly comprehensive use of the features provided by List Comprehensions. There's one more that I won't get into. So here's a module for building a deck of cards using List Comprehensions. Very trivial. You basically list out the two things that you combine across and you just have a List Comprehension. So that's very nice. I like this example. So let's have a look at structs. They're typed maps, so they're tagged maps with default values. So they're very easy to define. You define a function on your module named double underscore struct or underscore and you give it a map that it returns and it works. Of course, that's kind of a little bit funky feeling. So anyway, behind the scenes you can see that if you just generate a map with the struct key, it will actually turn it into a struct and it will get the default values. So that's kind of nice. Of course, nobody wants to define a function called underscore struct. So we have depth struct, which just looks nicer. And here we've got a struct that's a person and then this module is dealing with data that is in that pattern that looks that way. So that's nice. You can use the map update syntax to update structs and they'll verify that the data you're updating is a struct of the appropriate type. So if you were to try to update just a normal map with a structs update method, it'll fail. So that'll catch bugs if you accidentally pass the wrong type of value into a function. It'll crash right there instead of updating some address with the last name, which is what you might accidentally do. It's easy and convenient to pattern match on structs. So here's a pretty basic example. It sounds differently to people with the last name, Dootington. So anyway, that's nice. And again, pattern matching is an amazing feature. So the pipe operator, it's a nifty syntax for chaining functions and it lets you easily create a pipeline. So in Unix, a pipeline might look something like that. So this would list out the processes, grab the resulting lines for the string vim and print their PID. There's substantially better ways to accomplish this, but it serves a pretty comprehensible example. Most of what functional programming is is composing these small operations together. And so you'd expect that Elixir would handle this kind of thing well, and of course it does. Jose Crib did, I believe, from F-sharp. Although in F-sharp, it's partial application and Elixir is just syntactic sugar for passing its left side as the first argument to its right side. Anyway, but you end up with something like this. So this is a bit of Elixir functions that simulate that pipeline and they work just fine. And the reason that I think that this is really nice is if you were to unroll this pipeline, it would look like this. So it's really hard to just immediately understand that that one at the end is an argument to AUK. It's not immediately clear. On the top line, it's very, very obvious. So I think you end up with a lot more readable code when using pipes. You also run into the problem of using pipes about three to five times more often than you should. I certainly do that. So find it awesome and then back away from it probably when you realize that there's nothing but pipes on a file. Anyway, so real quick, we'll talk about recursion. Just covering it briefly as a concept. So here's how you would actually build a very basic recursion function. So this is a recursive function to sum a list and so we have the base case that's really the public API. It just says, hey, sum this list for me. And then the same sum list private function twice. So it takes a list as the first argument and an accumulator as the second argument. So we called it with an accumulator of zero. We then recursively call ourselves with the tail of the list and then we add the head of the list to the accumulator. And then when you call some list with an empty list, it just returns the accumulator. So this is how you basically unroll the list. So that's a nice feature that I've done recursive things in Ruby. It's scary, right? Because you have a limited stack and no tail call optimization. There's technically a way to make the Ruby VM detail call optimization, but it's not really something you want to depend on so much. Especially if you accidentally have your code running in a fiber and all of a sudden your stack is even smaller than you expect it to be. So anyway, very quickly on to processes. I'm going to cover what they are. We're going to play with them a bit and we'll look at encapsulating state. So what they are is just the unit of concurrency for Elixir. So this is the process and if you've heard people talking about the actor model, this is almost what they're talking about, although never say that on the Erlang questions mailing list or people will get really, really upset. So processes don't share any memory with each other and they can only communicate with each other via asynchronous messages. They're each garbage collected independently and so there's never going to be a stop the world GC like you'd have in Java or Ruby or wherever. And also these things can never block one another. So the way that Erlang's VM scheduler works is that each process in the system has its own operations which is just some unit of compute before moving on to the next one. And none of the operations can block the scheduler. So it'll also run across all your cores out of the box or all of your distributed nodes. So it's one of the most awesome things that Erlang provides. If you use processes and everything in your system is processes, it just gets to use a lot of hardware. Anyway, they're almost like objects. They're not really. But you can sort of treat them like objects. They can have internal state or you can make them act like they have internal state is really probably how you ought to do it. And yeah, I said they're independently garbage collected. All right, so here we define a new module, ping. It's a single function called await. And when await is called, it blocks waiting for a Pong message. Once it receives that message, it sends a ping message back to the sender who had to identify himself in the Pong message. So the Pong message is a Pong tuple with pit as the second element and the pit is the sender. So then you can see we spawn a new process running this function and we capture the process ID. This is important because this is the only way you can communicate with a process and that's by sending a message into its mailbox and to do that you have to have the process ID. We then send two Pong messages into its mailbox specifying our pit as the return pit and then we look at the messages we got back and it pinged us, so that's nice. So yeah, this is just neat. You can also spawn these processes on other machines so I could have that process that could have been on a separate machine and I could have pinged it and I wouldn't have to write any code any different. In Elixir, how do you model mutable state? Because it does exist. And that's with processes, so with a tiny tweak to what we had in the previous slide, we can build an object that can have its value incremented and decremented, which is very much like sending messages to objects in Ruby. So looking at this code, you can think of current value like an instance variable and these messages are receiving are like method calls. So for what it's worth, there's a pattern for the sort of thing in Erlang and it's called GenServer and there are also macros in Elixir for building GenServer more robustly built this thing and they're very succinct. So while here I'm showing you the underlying primitives, in general you're probably going to be using GenServer or the things that OTP provides. So anyway, there we go. I think this covers it right. You can send in an increment message and it will call itself again with the same number plus one. And so that's how you can encapsulate state and I think I thought this was very cool when I first saw how to do this. So that's that and that's very cool but you also tend to encapsulate state a fair bit. Anytime there's state, right, you have to ever represent it somehow and so you'd expect there to be an easier way to do this sort of thing and there is now. So this is where agents come in. So agents are simplified pattern for encapsulating state. So you can use them anytime you want to wrap state in a process and you don't intend to do anything more interesting with that process. So let's look how that works. So here we're starting new agent up and we're handing it a function that returns its initial state and we're also giving it a name. You could also just refer to it in the future by PID. So to update an agent you pass it a function that takes the agent state as an argument and it returns a new state for the agent. And so here we're putting bar into the key foo. In the map this agent is wrapping. Finally to get data out of an agent state you can pass it a function that receives the state as its argument and returns the data you're interested in. So here we're digging in to get the foo key back out. And you can stop an agent just so you know. They also support casts for asynchronous operations. So we could increment a counter as we did before. And it just works. And increment there is just a function that we've extracted that will do the update. So since these are casts our client doesn't wait until the operation is finished to return. That part happens in the agent process and it's important when dealing with agents to actually keep in mind whether you're in the client or the server. Because if you're blocking the server other clients can't talk to it. So here we've sort of simulated the work, right? So we've got a one second sleep. And so here assume that you're calculating a new value. You could calculate that value either on the server or on the client. If you calculate it on the server keep in mind that every other client will have to wait for that calculation to finish before it can talk to it. So in general it's probably better to calculate it on the client. In some cases you may not be able to avoid calculating it on the server. Anyway, so this is how that works. And then there are tasks. So these are another one of the newer features to Elixir. And so here they are. There are means of performing asynchronous operations with the ability to get the operation's value at a later time. So you can think of them as promises or asynchoate or futures. They serve basically the same purpose. So let's look at those. So here we've got a fairly basic bit of code. It maps a list of URLs to their titles. And implicit in this pipeline is actually fetching the URL from the internet, right? Which is a time consuming IO bound process. This code is sequential. So here we have the first site in the second site, then the third and so on. So we can use tasks to easily switch to fetching all these sites in parallel. So let's see what that looks like. So here we just map to a task that asynchronously does the previous work. And then we map all those tasks to their values with a weight. So this tiny change in code is all that it takes to turn that sequential bit of work into parallel work. And so suddenly the time to run this function went from the sum of all the times to the maximum time for the worst one. Which is nice. It's very, very nice to get that feature with one line of code. Anyway, so this basically wraps up the intro to Elixir Talk. And if anybody wants, I have these slides. If you'll ping me, I'll send them to you. Because I did kind of speed through it a little bit. But now we're going to talk about robots. So let us switch. All right. Hold that too. Okay, so talk number two. So I don't think we need to intro so much. I'm Josh, this is Ravi. Here's us on Twitter and GitHub. And R Clements, early factory robots is where you can find the code for this stuff. All right, so by the end of this talk, you'll be able to build an embedded app in Elixir that controls things in the physical world. And you'll be able to connect that app up to an Android interface. Which is a little more than the intro to Elixir. You'll also feel comfortable building these sorts of applications. Or at least you'll have a way to get over the humps. And you'll save a lot of frustration and missteps that you'd have had to deal with if you tried to do this on your own. Because we ran into a crap ton of them. And we overcame them all and documented them. All right, so this talk has a couple of parts. The first one's really just a brain dump. There's a lot of good information on what libraries are out there and focus sort of on easy wins. And after that, we dig into building a project together and we get a bit more complex with it. All right, so we'll go ahead and dive in so you guys can see what's out there. All right, so what is a robot? It's a force multiplier. It lets you take a simple action and cause a cascade of more complex decisions and actions. Lame! We're not actually going to have definition slides in this talk. We're going to have robots. So let's start with the hobby robotics. So hobby robotics just to take advantage of what Chris Anderson from Wired dubbed the peace dividend of the smartphone wars. Which is just an excellent quote. So we all know that processors and sensors like GBS and Bluetooth have gotten incredibly cheap. So it really gets to the heart of why that happened. And mass production of sensors for phones has made hobby robotics affordable and the maker movement has made it really approachable. These are just a few great resources. We keep these magazines around the office. But there's not as many client libraries out there for various robotics tools as other languages have. So for instance, we had to write the libraries for the Sphero and the AR drone before we could even play with them. Why is Elixir a good choice for this thing, Robbie? No good reason. We just did this for fun. But seriously, you know, the same reason as Elixir that we use it. We have concurrency, DSLs, metaprogramming and you can have fun writing your robots not just playing with them. So where should you start? Well, don't start with a giant project or do. But it's very easy to get bogged down with a small hardware problem like resistor values. Like when do I have to learn Ohm's Law? Just buy one of these toys and just get started playing with them. This guy here he's a Sphero. He's just a ball with a motor inside of him. He's Bluetooth controlled via serial port and you just he's really simple to play with. They're really good for teaching kids and keeping them engaged. They can see real world results of the code that they're typing. And this is us using our Sphero library. We start our Sphero client and we call roll square five times and then we call the stop function and then exit our process. It's pretty simple. Next we have our roll square function and that calls roll and sleep that takes the state and the angle and then lastly we have the roll and sleep function that calls roll. It passes the state a speed of 80 and then the angle. It doesn't get any easier. We're going to go ahead and demo this guy here. Put him down here for you. That's right. Groundbreaking. Oh, it's good. Okay, so it was really straightforward to port Tenderlove Sphero library from Ruby to Elixir. Dave pointed out don't do this, right? Don't write your Ruby in Elixir, but I wanted to get that thing to roll and it had a library sitting there and I didn't have the specs for it. So the Sphero library very basically consists of a piece that knows the commands that Sphero protocol responds to, a GIN server that can represent the ball connected to a given Sphero port and provide easy methods to issue those commands on the ball. So Sphero request is a module representing a given request to be sent down the Sphero port and so here we use a struct to represent a given request. It comprises the necessary fields to fully define the parameters for a request and it contains the functions that know how to turn those structs into the appropriate actual bit streams for the Sphero Sphero protocol. So you initialize it with the Sphero port attached to the Sphero and then you can just send it basic commands. It'll turn those commands into the corresponding request structs, generate their bit stream and send the bit stream down the Sphero port. And then the rest of the code is just convenience methods for building those various commands. So our next toy that we have is the pair of AR drawn also known as the Deathcopter. This guy creates his own Wi-Fi access point and you connect to him and you just send him UDP packets to control him. He's also got video cameras on him and you can probably get one for about 250 bucks for a new one or 150 for a refurb or 146,571 doge coins. Here's the basic example of us using our Extron module. We control takeoff, hovering, moving forward and landing in theory. Let's test that theory. Yeah, and so while I type this here I should point out that Chris McCord wrote another library for this and it's probably better than this one these days because I haven't really maintained this at all. Oh, no. Yeah, I know. Oh, cameras. Well, so just look at the actual thing if you can. You want to tell a story? Yeah, so this thing actually tried to kill our housekeeper when we were at ISKCON. We tested it in the hallway and that's why we just had it takeoff and land because it decided we didn't have the shroud on it and we're standing in the hallway and the thing just decides like Josh hits control C to kill it but he'd already sent the last command. It didn't look like it was actually connecting so I sent like half a command. It turns like almost 90 degrees and it's going at neck level down the hallway. Without that shroud, the blades were just exposed ready to main. And finally at the end it just slams to the wall and the housekeeper just like sticks her head out. Yeah, I'm already there. Yeah, so we also had to build this library. So let's have a look at it. The core of Xdrone consists of the drone server that represents a given pair at AR drone instance. So here you can see the broad layout of it. It uses three things, a UDP sender, an AT commander and a controller. And again, this is Ruby code ported. Later we have some straight elixir code talking to a thing and it's a little bit simpler. Anyway, so the UDP sender is the part of Xdrone that's responsible for actually sending the UDP packets to the AR drone and so here you can see it's a tiny, tiny veneer around gen UDP. But if you wanted to know how to do UDP, there you go. The next piece is called the AT commander due to the fact that the AR drones protocol look like AT commands from the old Hughes modem protocol. And so this is a server that gets ticked once every 30 milliseconds and he sends his current state via the UDP sender. So he keeps track of the state for what you want the drone to be doing and none of those states involve killing housekeepers. The controller is just a gen server that is interacting with the AT commander. It ultimately provides the nice interface that you use for manipulating pitch, roll, y'all and then it delegates to the drone server and sends its appropriate state updating commands. All right, so you've got your easy wins and you're still interested in doing more stuff so what do you do next? Microcontrollers are essentially tiny computers, right? What makes them special is that they're on a single board and they have a programmable I.O. So the Arduino showed up right around the same time that Make Magazine did and it had a huge impact on hobbyists and people that were doing microcontrollers before Arduino get really mad if you say it was important. Still, it's only a 16 megahertz device as no storage, no networking, it had to be programmed in C. So now we have a whole range of options from the Beagle 1 Black to the PCDuino which offers a 1 gigahertz chip, a gig of RAM, a Mali 400 GPU and an Arduino compatible pinout so you can take advantage of the existing marketplace of shields for the Arduino. But both of these are a lot more expensive and power hungry than the almighty Raspberry Pi. So with the Raspberry Pi you get 700 megahertz of compute, 512 megs of RAM and networking for $35 as well as a lot of GPIO to hook into. So it just hits a nice sweet spot. Also with the Pi you get several features. You have USB, it has LEDs, audio, RCA video, HDMI, LAN ports. But the main reason we use this thing is the GPIO pins or else it's just a really crappy computer. Setup's super easy too. It ships with the SD card already loaded with Raspbian Linux and it's ready to go. You just have to compile Erlang and Elixir. Erlang takes about three hours. You just fetch the sources, configure, make, make install. It takes a little longer. And Elixir takes about 20 minutes. You just do the same way that you normally do it. You can also cross compile them which is way smarter. It takes longer to set up. There's some things to take into consideration. You have limited hardware ports with modulation out of the box but we're going to show you how to get around this a little bit later. And you also need at least a one amp power supply to attach more stuff to it like a keyboard, mouse, Wi-Fi, Bluetooth adapter, webcam fidget sensors, like a compass, gyroscope, or accelerometer. Then you're going to need a multi-port USB hub. And we used the Pi Cobbler on ours. It's a ribbon cable that attaches to your GPIO pins and attaches that to a breadboard. It makes connecting off the pins much easier to manage. There's a $11 Serago USB Wi-Fi Bluetooth adapter. It's great for basic IO and it's low-powered. Cases will keep you from shorting it out. This is my second one. You can put some heat sinks on it to overclock it. And since we're on the subject of microcontrollers, I want to point out that we've been looking at it a lot more lately. And I don't know the exact processors on some of them, but we saw one with an 8-core processor and that's pretty cool because, you know, elixir. So we used Erling L for our GPIO access in at least one of our projects. It's an Erling library and we're using it in elixir. It's a normal thing to do. And here you can see a simple example of just outputting to a pin. So say we have an LED and it's hooked up to a pin 25 of our Pi. Well, we can turn pin 25 on. We can sleep and then turn it back off just like that. And there's lots of ways to control hardware. There's serial ports. You can write to like you're appending to a text file. You can attach a Bluetooth, USB, or GPIO. But this is elixir, right? So in elixir you have distribution. And this is my favorite way to actually talk to things, right? You're just sending messages to them. And so since it's the default way for Erling and elixir to communicate, we figured we'd do that. And it turns out it's fantastic for building simple robots. So we're going to move on to the second part where we actually build a thing. Let's build something. We won't spend long on that. All right, so we got some easy wins with these toys. And we showed how to take a microcontroller and make an LED blink. But we can do better than that. Going forward, we're going to have a lot of quick code. Our goal is not going to be to provide code examples. All of our code and in Ruby as well is on GitHub if you guys want to see it. Okay, so blinking an LED from elixir is really cool. But how can you get more direct control of the robots? Typically you might expect to provide your own serial protocol the way the Sphero or the Aerodrome does. But one of the Beam's big selling points is the distribution that I talked about. So what I wanted to be able to do was communicate from an Android device directly to a remote Erlang process. Of course, this is possible thanks to J-interface which ships with Erlang. So our goal is go from Android using the J-interface library, talk directly to an elixir process remotely, have it control the Raspberry Pi GPIO and blink a freaking light. Okay, so there are a few hurdles in the way of just doing that. First is J-interface. It took us a while to figure it out, so I wanted to just kind of go over it. J-interface just doesn't work if you don't have EPMD running on the host. So this is the Erlang portmapper daemon. This is the way that Erlang networks know how to talk to who. So that meant we had to figure out how to ship and start Erlang on an Android host. I'd love to talk about how we did this because it wasn't very clear. Our application had to launch the processes on the underlying Linux OS under Android because of Android sandboxing. And so before we could launch the processes, we had to actually get them onto the Android file system with our application. And so looking at that real quick, we're going to cover some Java code because it's elixirconf. So here you can see the code we attached to a couple of buttons in our app to copy Erlang onto the file system and launch EPMD as well as just an Erlang node. So basically we just copy it there. We make it executable and then we run the commands. Here's the Android device actually having the Erlang copied out of a zip package with the Android app onto the Linux file system underlying the device. And you have to do this once for each Android application. You do this sort of thing with presently. Ultimately, you just end up with an Android app that contains a button and that button triggers some J-interface calls. So each of these button presses is going to send a gencast to a toggle function on a remote gen server that's running on the Raspberry Pi. So here you can see what one of those casts looks like. So when you call cast in OTP, all that's really happening is you're sending a message that is a tuple whose first element is the $adam gencast and then that contains a tuple containing the message. Anyway, so that's that. So we can send messages. Let's look at the elixir side. So here we've used xactor, which is a great library, to build a basic gen server responsible for toggling a pin. So our initial state is a tuple representing the state of the pin. It starts out off. And then you can call toggle on it and it'll flip the state every time you call it. And then it'll also update the state on the GPIO pin. So next we run the server. We register it with the Adam LED. We have to do this cookie thing. You have to have a cookie if you want these nodes to talk to each other. And with that we basically close the loop. So enough with the theory. Let's see if this thing works. Okay, so what's the next obvious step past a single red LED? It seemed like an RGB LED was the next move. So let's make that happen. So you can use pulse width modulation. It's really meant for sending like logic across a single wire. But you can also use it to simulate analog levels. All you're doing is you're switching the pin on and off. And so if an output pin is switched on for 10% of the time and it's evenly distributed, then as far as like the LED knows, it's just getting a 10% signal. So later we use them for logic level, but here we treat PWM like fake analog. And like I said earlier on the Raspberry Pi, you only get one PWM pin. But we need at least three for this RGB project. So we use the Pi Blaster library and that gives us eight software PWM outputs. So here's how we use the Pi Blaster. You're just echoing commands to the device file. So here we're controlling pin 23 and zero would be 0% signal. One is a full signal and 0.2 is just a 20% signal. All right, so here's a basic module representing our RGB LED. And this is old elixir. It has records in it. Just pretend that they're structs. Okay, so this is a normal stateless module. It uses a couple of records to represent a single pin and the full RGB LED component. The init function generates a component representing the LED. And it also supports a set value function and a Pi Blast function. When we Pi Blast, we actually invert the value that's set in the component. And this is because when you deal with like hardware, you have quirks, right? So the RGB LED we got was common cathode. That meant we really had to modulate ground in the reverse of what you wanted to actually make it turn on the intensity you desired. Anyway, then we wrap that up with a basic GIN server that we exposed via Erlang distribution, just like you saw before. So very basic. It just provides those external calls. And then on the Android device, we have a basic color picker. So there's nothing fancy here. As you change the slider, we want the LED to update in real time. So the way we do that is we sample the interface a bunch of times per second. So we see what the interface looks like 20 times a second or 10 or whatever this code says. And then we send those messages using J-interface. So here's the timer. And here's how you can prepare yourself to talk to a remote node. You can see we create a mailbox for ourselves, and then we just ping the remote node. And this sets up the Erlang distribution between the Android device and the Raspberry Pi. And here's that casting with a GIN server from J-interface, which we saw a little bit ago, slightly more detailed, but not basically the same thing. So here's that demo. All right. There's my beard. All right. So we have pulse width modulation control of an Elixir process from Android. So what's next? Well, this guy down here, he's the RAD2. We have his tank steering base. And you can get one at thrift stores just like him for about two to five bucks if you haggle. And what was once loved by a child only to be thrown away can be yours to love again. But it's going to be way more awesome this time. So we're going to finish up and build an RC tank steering thingy. All right. So you need a Sabertooth 2x12 RC. It costs about 65 bucks. You add a Raspberry Pi. Yeah. You add a 12 volt battery. Okay. You add that Sorago Wi-Fi Bluetooth dongle. You mutilate a USB micro cable. And you put it all together and you end up with this. So Sabertooth logic levels. The Sabertooth basically takes PWM logic signals. I'm going to skip a little bit about the discussion with Sabertooth, and you'll know why in a second. So here's the interface from Android. There's just two sliders. They're mapped from negative one to one. These are standard tank steering controls. Here's our Java code that generates the Jinterface calls to send the appropriate messages. Again, very, very similar to what you saw before. Hook it all together and we end up with a remote control interface for a tank. So let's look at the elixir code. So here we have a motor module. So this represents a single motor. And it takes the motor's pin when initializing it. It supports a set speed function. And this maps the value it was given to the appropriate pulse with modulation levels. Returns the pin, updated with the new mapped value. Mapping the value is just basic math. Here's our tank module controlling two motors. It's not hard to follow or terribly relevant when I get to a few slides later. And then here you can see a quick server we wrapped around the tank module. So this is what our Jinterface is ultimately sending messages to. And it uses the tank as its state. And then it defines a couple of casts. We're totally on time. So here's how we run it. We spin up an Erlang node and just like we did before. And so here's where you normally would be showing the tank demo. But. So our server truth controller decided to stop working when we were at Oskon. Four o'clock we tested it. 430 it stopped working. And this is the day before our talk. So that was good. So we started calling around and nobody had any replacements at the hobby shops that would work for us. So we had to ask ourselves is our talk ruined? Well around five o'clock we went to Radio Shack and we purchased, well she was talking crap about earlier, an Uno and then we got our Arduino motor shield and various assorted tools and wiring and we got to hacking. We wired everything up giving the tank a bit of an overhaul and we essentially just used the saber tooth now as a rich man's voltage converter. That poor Razz Pie has no PWM hookups on him. But he's still the brain of the operation. So yeah here you can see our midnight commits. They were more than this. But this is what our trip turned into. We went to a single Oskon talk by the way. Anyway so here's basic midnight code quality Arduino code. We defined a protocol to control the motors via the serial port. And then once that was working we had to write an elixir library to wrap it with. So here's a module that knows how to speak our ad hoc serial protocol. And this is the driver that handles creating the serial port connection. We didn't have to change very much in the actual tank. And yeah so here we go. Let's see if it works. Anyway so elixir control of a tank via Android. Questions? We have 20 second questions.