The Twor-Bot

IoT With Phoenix Part 3

| Comments

This is the last part in the series.

In the previous blog post, the browser client was getting messages from the elixir interpreter inside the project directory using the Endpoint.broadcast method. Now, for monitoring sensor outputs, we have to send and receive data from sensors, we need to remotely configure a client. I am using a raspberry pi with python GPIO module to interface the sensors. So, we are going to accomplish the following tasks in this part 3.

  1. Join the phoenix channel and send a random value form a python client using websockets.
  2. Sending data from the serialport. (Sensors)

The Phoenix channel API is damn easy to understand. It has phx_join event is for joining a channel, phx_reply for a reply after join. Following the previous blog, we have a event called sensoroutput with a topic `users:usertoken` (user_token is the token generated for a user). So, the following python code is capable of joining the channel topic and sending a sample random value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import asyncio
import websockets
import json
import time
from random import randint

async def hello():
    async with websockets.connect('ws://127.0.0.1:4000/socket/websocket') as websocket:
        data = dict(topic="users:your_user_token", event="phx_join", payload={}, ref=1)

        #data is a dictionary containing necessary info for a join request to the topic.

        await websocket.send(json.dumps(data))
        print("joined")

        print("Joined") #joined the topic user:user_token
        while True:
            msg = await retrieve() #waiting for retrieve function to return a value

            await websocket.send(json.dumps(msg))
            #sending the message to the phoenix channel

            call = await websocket.recv() #constantly receiving data from the channel
            control = json.loads(call) #converting to json
            print(control)

            time.sleep(0.5) #0.5 second delay

    async def retrieve():

      msg = dict(topic="users:your_user_token", event="sensor_output", payload={"load":"1000", "pf":str(randint(0,100)), "thd":"120", "reading":"1800"}, ref=None)

      #message dictionary containing necessary info for sending the data to the channel
      time.sleep(0.5)
      return msg


asyncio.get_event_loop().run_until_complete(hello())
asyncio.get_event_loop().run_forever()
` This is a piece of asynchronous code written in python, in which it joins the phoenix channel and waits until data comes form another function and sends it to the phoenix server. Now if we run this script, we can see the data updated in the webpage from time to time with random values. Now, there was a outward message from the channel too through the `control` event. We can keep track of that too (The button click events of blog post 2) just by comparing the `event` key of the json string `control`. If the event name is `control`, we can make use of that too.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import asyncio
import websockets
import json
import time
from random import randint

async def hello():
    async with websockets.connect('ws://127.0.0.1:4000/socket/websocket') as websocket:
        data = dict(topic="users:your_user_token", event="phx_join", payload={}, ref=1)

        #data is a dictionary containing necessary info for a join request to the topic.

        await websocket.send(json.dumps(data))
        print("joined")

        print("Joined") #joined the topic user:user_token
        while True:
            msg = await retrieve() #waiting for retrieve function to return a value

            await websocket.send(json.dumps(msg))
            print("sent {}".format(msg))
            #sending the message to the phoenix channel

            call = await websocket.recv() #constantly receiving data from the channel
            control = json.loads(call) #converting to json

            if(control['event'] == 'control'):
                print(control['payload']['value'])

            time.sleep(0.5) #0.5 second delay

async def retrieve():

    msg = dict(topic="users:your_user_token", event="sensor_output", payload={"load":"1000", "pf":str(randint(0,100)), "thd":"120", "reading":"1800"}, ref=None)

    #message dictionary containing necessary info for sending the data to the channel
    time.sleep(0.5)
    return msg


asyncio.get_event_loop().run_until_complete(hello())
asyncio.get_event_loop().run_forever()

This script prints the payload value if the event name is control. That is when there is a button click event, it will print on or off depending on the buttons.

Now, let’s write some code where we can get data from the serialport. All you need is the pyserial library and receiving some data from there like the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
import serial

ser = #ser =serial.Serial("/dev/ttyAMA0", 9600, timeout=1)

#rest of the code

async def retrieve()

  data = ser.readline().decode()
  msg = dict(topic="users:your_user_token", event="sensor_output", payload={"load":"1000", "pf":str(randint(0,100)), "thd":data, "reading":"1800"}, ref=None)

  return msg
  #rest of the code

Here the data will be received from the serialport and will be updated at thd on the webpage.

There are several other examples I have written, by using those in raspberry pi, we can send and receive data from the websocket phoenix server. Examples include some arduino firmata codes too.

Python clients are here.

P.S. I have moved to another city for my first ever job. This is my first blog post from Bangalore city. Happy Hacking ! :D :)

Iot With Phoenix Part 2

| Comments

In part 1, I have demonstrated how to create MVC based user authentication and a plug for the same with Phoenix. Now, in this tutorial we will see how to display some data using websockets. Websocket connections are consistent. So, for displaying the real time data from the machine, we need to use the channel feature of phoenix, where we can update the data on the page in real time.

  1. The channel should be user specific. Users can view their own sensor outputs of the machines that they have privately.

  2. There should be a reverse communication from users to machines. With this, users can be able to switch on or off the machine along with some other things like controlling speed, displaying something on a LCD screen and so on.

So, let’s create a channel for the users. We will make use of something that will let us make the users’ communication private with their machines.

$mix phoenix.gen.channel User

It will create a file called user_channel.ex in web/channles/ directory. It contains the following,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
defmodule Iot.UserChannel do
  use Iot.Web, :channel

  def join("user:lobby", payload, socket) do
    if authorized?(payload) do
      {:ok, socket}
    else
      {:error, %{reason: "unauthorized"}}
    end
  end

  # Channels can be used in a request/response fashion
  # by sending replies to requests from the client
  def handle_in("ping", payload, socket) do
    {:reply, {:ok, payload}, socket}
  end

  # It is also common to receive messages from the client and
  # broadcast to everyone in the current topic (user:lobby).
  def handle_in("shout", payload, socket) do
    broadcast socket, "shout", payload
    {:noreply, socket}
  end

  # Add authorization logic here as required.
  defp authorized?(_payload) do
    true
  end
end

The join method has a argument user:lobby by default. It is called the topic:subtopic pair. The topic here is user and the subtopic is lobbby. The handle_in method has the first argument as ping or shout. Those are called events. Once a user is joined to the subtopic, the handle_in methods can show what messages are coming to that subtopic through an event and that handle_in method can also broadcast a message upon arrival through an event. Other subscribers (who have joined to that same subtopic) can get the message through that event.

Making an analogy with our required task, we need to make the subtopic unique for each user. Then we need to create 2 events. One for displaying stuff on a webpage through an event broadcast (broadcasting to a particular event), the other is to broadcast the reverse message from the user to control stuff at the machine. Let’s name those 2 events as sensor_output and control. So, our version of user_channel.ex is given below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
defmodule Iot.UserChannel do
  use Iot.Web, :channel

  def join("users:" <> user_token, payload, socket) do
    if authorized?(payload) do
      {:ok, "Joined To User:#{user_token}", socket}
    else
      {:error, %{reason: "unauthorized"}}
    end
  end

  # Channels can be used in a request/response fashion
  # by sending replies to requests from the client


  def handle_in("control", payload, socket) do
    broadcast socket, "control", payload
    {:noreply, socket}
  end

  def handle_in("sensor_output", payload, socket) do
    broadcast socket, "sensor_output", payload
    {:noreply, socket}
  end

  # Add authorization logic here as required.
  defp authorized?(_payload) do
    true
  end
end

Now, from the above user_channel, it’s clear what the two handle_in methods do on arrival of a new message. They just broadcast it to the respective events. But the join event has the subtopic to be added to the topic users. The subtopic we are using is the user_token that is saved as a string in the Users table whenever a user registers in the application. It has been written in the Password library, refer to the previous blog post. Now, we have to tell our socket file to enable the users topic with a wild card subtopic. Add the following line.

1
2
#web/channes/user_socket.ex
channel "users:*", Iot.UserChannel

All set with the background process handlers. Now, let’s move to the front-end. We need a webpage to show all the messages that comes through sensor_output event. Before that, the webpage has to be joined with the users:user_token topic:subtopic. The front-end we will automate with some JS code. Before that, the JS code should have the knowledge of the user_token, otherwise it can’t be able to join the topic. A plain JS code can’t invoke the user_token from the database directly. So, we need to take that user_token from that very template where we want to show the content. The question is, where shall the template render the user_token from ? The answer is pretty simple. From the controller it has been associated with. Voila ! now we have figured out what to do. So, let’s make a model called energy_meter. The model wil be used later. For now, we will use a template only. We are not doing anything with the model now. It’s just for a future use.

$mix phoenix.gen.model EnergyMeter energy_meters name:string pf:integer reading:integer thd:integer load:integer

Then let’s change the template under the folder energy_meter inside the templates folder. The controller is given below.

1
2
3
4
5
6
7
8
9
10
11
#web/controller/energy_meter_controller.ex
defmodule Iot.EnergyMeterController do
  use Iot.Web, :controller

  plug Iot.Plug.Authenticate

  def index(conn, _params) do
    current_user = get_session(conn, :current_user)
    render conn, "index.html", current_user: current_user
  end
end

The template is given below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#web/templates/energy_meter/index.html.eex
<ul id="em" data-id=<%= @current_user.token %>>

</ul>
<div class = "container">
  <div class = "row">

    <div class = "span4">
      <h4>Load</h4>
      <div id = "load">
      </div>
    </div>



    <div class = "span4">
      <h4>Power Factor</h4>
      <div id = "pf">
      </div>
    </div>



    <div class = "span4">
      <h4>THD</h4>
      <div id = "thd">
      </div>
    </div>



    <div class = "span4">
      <h4>Reading</h4>
      <div id = "reading">
      </div>
    </div>


</div>




  <div class = "btn btn-primary" id="on">ON</div>
  <div class = "btn btn-primary" id="off">OFF</div>
  <%= link("Logout", to: session_path(@conn, :delete), class: "btn btn-success pull-right") %>
</div>

In this way the user_token has been retrieved on to the template. Form the data-id of that division, we can take away that value to our JS files.

Now, the html part is done. Let’s write the JS parts to automate the process. Using jQuery is a better option here as far as ease of writing code is concerned. In the parent directory of the project a bower install will install jQuery libs for us.

$bower install

Now, let’s create a user.js file in web/static/js folder. Before writing something, let’s comment the default code for joining a topic:subtopicin socket.js

1
2
3
4
//let channel = socket.channel("topic:subtopic", {})
//channel.join()
  //.receive("ok", resp => { console.log("Joined successfully", resp) })
  //.receive("error", resp => { console.log("Unable to join", resp) })

Now, the content to write in the user.js file is below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
   import socket from "./socket"

  $(function() {
    let ul = $("ul#em")
  //let message = $("div#message") 
    if (ul.length) {
      var token = ul.data("id")
      var topic = "users:" + token
          
      // Join the topic
      let channel = socket.channel(topic, {})
      channel.join()
        .receive("ok", data => {
          console.log("Joined topic", topic)
        })
        .receive("error", resp => {
          console.log("Unable to join topic", topic)
        })
              

              $("#on").click(function(){
                      channel.push("control", {val: "on"});
              })
              $("#off").click(function(){
                      channel.push("control", {val: "off"})
              })

              channel.on("control", data => {
                      console.log("Recieved: ", data.val);
              })
              channel.on("sensor_output", data => {
                  $("#load").html(data['load']);
                  $("#pf").html(data['pf']);
                  $("#thd").html(data['thd']);
                  $("#reading").html(data['reading']);
              })
              
    }
  });

This code fetches the value of token from u.data("id") from that html template. The topic variable is the concatenation of users and the token. Then the JS client joins the topic. On join, the topic:subtopic is printed on to the console of that web page. Then, there are some event based automation is written. When the button with id on is pressed there at the webpage, the data val: "on" is sent via the control event. And similarly for the off button, the data is sent via control event. Again here, the message is handled and printed on to the console with the following.

1
2
3
channel.on("control", data => {
  console.log("Recieved: ", data.val);
})

So, we can view on the console what the value has been sent from the on and off buttons. Then the next method in the file displays the sensor_output data on to the page. Now, let’s add this file to the app JS file so that it can be added to all the templates.

1
2
   // web/static/js/app.js
   import user from "./user"

Now, the button press evens can be tested. Remember, that console messages on and off can only be seen for a user if he/she is logged in.

For the sensor_output event, let’s broadcast something over that event from the interpreter.

$iex -S mix phoenix.server

Then using the Endpoint.broadcast method we can broadcast a message over a event within a topic.

iex(2)> Iot.Endpoint.broadcast("users:anVhbkBnbWFpbC5jb21qdWxpYTEyMw==", "sensor_output", %{"power_factor" => 23, "load" => 1000, "thd" => 4, "reading" => 1800})
:ok
iex(3)> Iot.Endpoint.broadcast("users:anVhbkBnbWFpbC5jb21qdWxpYTEyMw==", "sensor_output", %{"power_factor" => 04, "load" => 900, "thd" => 2, "reading" => 1900})
:ok

As soon as you run, you can see the values updating automatically on the webpage. Similarly, for the control event, just clicking the on and off buttons will do what we want. It will print the message on to the console. A demo screen recording of that is given below. My project name was tworit so I used Tworit.Endpoint. Likewise, here, Iot.Endpoint can be used.

phoenix_channels from Tworit on Vimeo.

In the next part, we will do some python 3.5 asyncio. With the help of that, we can send data from a raspberry pi to the sensor_output event. In addition to that, we can receive the on and off signals from the server to turn on and off our machine.

IoT With Phoenix Part 1

| Comments

This is the first blog post that I am writing to share my experience with the Phoenix framework in building an Iot application. I have written a blog post about Elixir and Phoenix here. The objectives that we are going to achieve in here are

  1. A ‘Model View Controller’ scheme for the users. So that the users can register themselves in the application and have a login access to monitor as well as control their machines.

  2. A messaging interface between the machine and the user so that the application can be pretty much asynchronous and fast. This will accomplish the goal of an user specific Iot architecture, where a user can control and monitor only his/her machines, not others. There is no need of refreshing the pages to know the current state of the machines as we will be using websocket connections to make it a real time application, where the connection to the server never goes away.

  3. Writing machine clients. The clients which will help the machine send sensor outputs to the server.

Phoenix is a framework written in Elixir programming language which runs on Erlang VM. The installation instructions for the framework is given here. After successful installation, let’s start building the application.

To create our Iot project run the following in the terminal.

$mix phoenix.new iot

Now, enter into the application. Note: you must have postgres installed in your system for the database requirements.

$cd iot

Now run the server or you can run the server within an interpreter too.

$mix phoenix.server 

or

$iex -S mix phoenix.server 

Now we can view the application at http://localhost:4000/. Now let’s change the contents of some files to have the default page as the login page for users. To achieve that, we should have an users table in the database with the details of the users as attributes. For that, we have to generate a users model using the mix model generator.

$mix phoenix.gen.model User user username:string encrypted_password:string email:string token:string 

It will create a file called user.ex in the web/models/ directory. Now the users table has 4 attributes called the username, encrypted_password, email and a token. But, to register a user with a password for login purposes, we should have two virtual fields, the password field and a password_confirmation field. These are virtual attributes and they are never stored as attributes of the users table. The password after entered in the registration form is converted into a encrypted form and saved in the database as encrypted password. When the user logs in later, again that entered password is encrypted and matched with the encrypted password already saved in the database for that user. This process helps in a secured access by not storing the password anywhere during the login or register process. The user only knows his password, no one else knows, not even the admins of the application. :D

Now, let’s add those virtual fields and have some validations for the attributes in user.ex file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
defmodule Iot.User do
  use Iot.Web, :model
  alias Iot.Repo

  schema "users" do
    field :username, :string
    field :email, :string
    field :encrypted_password, :string
    field :password, :string, virtual: true
    field :password_confirmation, :string, virtual: true
    field :token, :string
    timestamps
  end


  @required_fields ~w(username email password password_confirmation)
  @optional_fields ~w()

  @doc """
  Creates a changeset based on the `model` and `params`.

  If no params are provided, an invalid changeset is returned
  with no validation performed.
  """
  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
    |> unique_constraint(:username, on: Repo, downcase: true)
    |> validate_length(:password, min: 8)
    |> validate_length(:password_confirmation, min: 8)
    |> validate_confirmation(:password)
  end
end

Here, the required fields doesn’t include the encrypted_passwordfield and the reason is obvious. The encrypted_password we are going to generate later. Now, to register the users, we should have a registration controller, a registration template of course with a form to be filled by the users, and a url like http://localhost:4000/registraion. So, let’s modify the web/router.ex file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
defmodule Iot.Router do
  use Iot.Web, :router


  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", Iot do
    pipe_through :browser # Use the default browser stack
    get "/registration", RegistrationController, :new
    post "/registration", RegistrationController, :create
    get "/", PageController, :index

  end

end

Now we have added 2 routes, one to get the content (The user registration form) and the other is a post request for the same. Now we need to have a registration_controller.ex file in the web/controller directory, where we are going to write the new and create methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
defmodule Iot.RegistrationController do
  use Iot.Web, :controller

  alias Iot.Password

  def new(conn, _params) do
    changeset = User.changeset(%User{})
    render conn, changeset: changeset
  end

  def create(conn, %{"user" => user_params}) do
    changeset = User.changeset(%User{}, user_params)
    if changeset.valid? do
      new_user = Password.generate_password_and_store_user(changeset)
      conn
        |> put_flash(:info, "You are Sucessfully Registered :P ")
        |> redirect(to: page_path(conn, :index))
    else
      render conn, "new.html", changeset: changeset
    end
  end
end

Here in the new method, we are accepting the attributes of the user in the variable changeset. The create method checks if those required fields fulfill the validations present in web/models/user.ex by changeset.valid? method and stores the user in the database and renders the page_index page. (The default page at http://localhost:4000/ ). If the changeset.valid? is not fulfilled again the new registration page will open up.

The saving of the user in the database by creating the encrypted_password is done here by the Password library. Let’s write the password library with the generate_password_and_store_user that we have just used in the registration controller and other methods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#lib/Iot/password.ex
  defmodule Iot.Password do
      alias Iot.Repo
    import Ecto.Changeset, only: [put_change: 3]
    import Comeonin.Bcrypt, only: [hashpwsalt: 1]


    def generate_password_and_token(changeset) do
      to_be_encoded_string = Enum.join([changeset.params["email"], changeset.params["password"]])

      token = Base.encode64(to_be_encoded_string)
      changeset = put_change(changeset, :token, token)

      put_change(changeset, :encrypted_password, hashpwsalt(changeset.params["password"]))
    end


    def generate_password_and_store_user(changeset) do
      changeset
        |> generate_password_and_token
        |> Repo.insert
    end
  end

Here I have used comeonin package to encrypt the password. You can get it by adding it to the dependencies in the mix.exs file as

1
2
3
4
5
6
7
8
9
10
defp deps do
    [{:phoenix, "~> 1.1.4"},
     {:postgrex, ">= 0.0.0"},
     {:phoenix_ecto, "~> 2.0"},
     {:phoenix_html, "~> 2.4"},
     {:phoenix_live_reload, "~> 1.0", only: :dev},
     {:gettext, "~> 0.9"},
     {:cowboy, "~> 1.0"},
    {:comeonin, "~> 2.5"}]
  end

Then install it through

$mix deps.get 

The generate_password_and_token method generates the encrypted password and a token(to be used later) for the user. The generate_password_and_store_user method stores the user in the database. Now, it’s time to add a template for the new registration page. Create a directory named registration in the templates folder and add a new.html.eex file in it. Fill it with the content below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<h3>Registration</h3>
<%= form_for @changeset, registration_path(@conn, :create), fn f -> %>
  <%= if f.errors != [] do %>
    <div class="alert alert-danger">
      <p>Oops, something went wrong! Please check the errors below:</p>
      <ul>
        <%= for {attr, message} <- f.errors do %>
          <li><%= humanize(attr) %> <%= translate_error(message) %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="form-group">
    <label>Username</label>
    <%= text_input f, :username, class: "form-control" %>
  </div>

  <div class="form-group">
    <label>Email</label>
    <%= text_input f, :email, class: "form-control" %>
  </div>


  <div class="form-group">
    <label>Password</label>
    <%= password_input f, :password, class: "form-control" %>
  </div>

  <div class="form-group">
    <label>Password Confirmation</label>
    <%= password_input f, :password_confirmation, class: "form-control" %>
  </div>

  <div class="form-group">
    <%= submit "Register", class: "btn btn-primary" %>
    <%= #link("Login", to: session_path(@conn, :new), class: "btn btn-success pull-right") %>
  </div>
<% end %>

The session_login button is now commented because we haven’t added the sessions controller yet.

Let’s try it all out. First we have to create the database for the application using ecto.

$mix ecto.create

Then, we have to migrate the changes that we have in the users model.

$mix ecto.migrate

Now we have to restart the server as we have added a new lib file called password.ex. Then, check if that registration form at http://localhost:4000/registration/ is working. If it renders the default phoenix page with a “You are Sucessfully Registered :P”, it’s working.

Now let’s replace the default phoenix page with a login page for the users. Let’s understand what a session is. Sessions are the users’ active time spans after login. A sessions controller matches the username and password of the user and renders the pages. A session controller stores the users data (you can customize the data to be stored) for the session. It is recommended to store minimum required data like only the username or the email in the session. With a logout request, we free the session variables. So, now we have to add a login and a logout route in the router.ex along with a new route for the session. The page route will be replaced by the new method of the session.

1
2
3
4
5
6
7
8
scope "/", Iot do
    pipe_through :browser # Use the default browser stack
    get "/registration", RegistrationController, :new
    post "/registration", RegistrationController, :create
    get "/", SessionController, :new
    post "/login", SessionController, :create
    get "/logout", SessionController, :delete
end

Clearly from the routes, we now know that we have to write a session_controller.ex in the web/controllers directory with new, create and delete methods in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#web/controllers/session_controller.ex
defmodule Iot.SessionController do
  use Iot.Web, :controller

  plug :scrub_params, "user" when action in [:create]
  plug :action

  def new(conn, _params) do
    render conn, changeset: User.changeset(%User{})
  end

  def create(conn, %{"user" => user_params}) do
    user = if is_nil(user_params["username"]) do
      nil
    else
      Repo.get_by(User, username: user_params["username"])
    end

    user
      |> sign_in(user_params["password"], conn)
  end

  def delete(conn, _) do
    delete_session(conn, :current_user)
      |> put_flash(:info, 'You have been logged out')
      |> redirect(to: session_path(conn, :new))
  end

  defp sign_in(user, password, conn) when is_nil(user) do
    conn
      |> put_flash(:error, 'Could not find a user with that username.')
      |> render "new.html", changeset: User.changeset(%User{})
  end

  defp sign_in(user, password, conn) when is_map(user) do
    cond do
      Comeonin.Bcrypt.checkpw(password, user.encrypted_password) ->
        conn
          |> put_session(:current_user, user)
          |> put_flash(:info, 'You are now signed in.')
          |> redirect(to: energy_meter_path(conn, :index))
      true ->
        conn
          |> put_flash(:error, 'Username or password are incorrect.')
          |> render "new.html", changeset: User.changeset(%User{})
    end
  end
end

The code above is self explanatory. The sign_in method lets the user log into the pages. The put_session method stores temporary session data. In this case the user is saved in the session as :current_user. Now, we will write the new template for the login form. Create a folder called session in the web/templates/ folder and a file called new.html.eex in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<h3>Login</h3>
<%= form_for @changeset, session_path(@conn, :create), fn f -> %>
  <%= if f.errors != [] do %>
    <div class="alert alert-danger">
      <p>Oops, something went wrong! Please check the errors below:</p>
      <ul>
        <%= for {attr, message} <- f.errors do %>
          <li><%= humanize(attr) %> <%= translate_error(message) %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="form-group">
    <label>Username</label>
    <%= text_input f, :username, class: "form-control" %>
  </div>

  <div class="form-group">
    <label>Password</label>
    <%= password_input f, :password, class: "form-control" %>
  </div>

  <div class="form-group">
    <%= submit "Login", class: "btn btn-primary" %>
    <%= link("Sign Up", to: registration_path(@conn, :new), class: "btn btn-success pull-right") %>
  </div>
<% end %>

Now, we can uncomment the line in web/templates/registration/new.html.eex for the session login path. And we change the create method of the registration controller to render the login page rather than the default phoenix page.

1
2
3
4
5
6
7
8
9
10
11
def create(conn, %{"user" => user_params}) do
    changeset = User.changeset(%User{}, user_params)
    if changeset.valid? do
      new_user = Password.generate_password_and_store_user(changeset)
      conn
        |> put_flash(:info, "You are Sucessfully Registered :P ")
        |> redirect(to: session_path(conn, :new))
    else
      render conn, "new.html", changeset: changeset
    end
end

Now, where will it go after login? We must have some place where it should move to after login and we must have a control over that page so that that page can not be opened unless the user is logged in. That is why the line redirect(to: energy_meter_path(conn, :index)) is added in the sign_in method (EnergyMeter is our Iot device). We will create a energy_meter template with only the username of the user in it. At first, let’s edit the router.ex file.

1
2
3
4
5
6
7
8
9
scope "/", Iot do
    pipe_through :browser # Use the default browser stack
    get "/registration", RegistrationController, :new
    post "/registration", RegistrationController, :create
    get "/", SessionController, :new
    post "/login", SessionController, :create
    get "/logout", SessionController, :delete
    get "/em", EnergyMeterController, :index
end

Now let’s create a energy_meter_controller.ex.

1
2
3
4
5
6
7
8
9
10
defmodule Iot.EnergyMeterController do
  use Iot.Web, :controller

  plug Iot.Plug.Authenticate

  def index(conn, _params) do
    current_user = get_session(conn, :current_user)
    render conn, "index.html", current_user: current_user
  end
end

Now let’s write the template for this.

1
2
3
#web/templates/energy_meter/index.html.eex
<div>Hi <%= @current_user.username %></div>
<%= link("Logout", to: session_path(@conn, :delete), class: "btn btn-success pull-right") %>

This has the username of that user and a logout button. The controller has a Authenticate Plug, which ensures the authenticity of the current user. If the user is not logged in, this Plug helps not to show any page in the EnergyMeter controller. Let’s write that Plug. We have to create a directory called authentication in the web directory and add authenticate.ex file in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
defmodule Iot.Plug.Authenticate do
  import Plug.Conn
  import Iot.Router.Helpers
  import Phoenix.Controller

  def init(default), do: default

  def call(conn, default) do
    current_user = get_session(conn, :current_user)
    if current_user do
      assign(conn, :current_user, current_user)
    else
      conn
        |> put_flash(:error, 'You Need to be signed in to view this page !')
        |> redirect(to: session_path(conn, :new))
    end
  end
end

The code is self explanatory. If a user is trying to get the energy_meter index page without logging in, it will throw the error as “You Need to be signed in to view this page !”. Now try that all out by going to http://localhost:4000/.

Note: a view must be added with all the controllers. Otherwise, it will throw an error. A demo view in the views folder is given below.

1
2
3
4
#web/views/session_view.ex
defmodule Iot.SessionView do
          use Iot.Web, :view
end

Now, the authentication part is done. In the next part, we will code the messaging application that is needed for users to listen and control their machines.

Happy Hacking !

Reference - http://meatherly.github.io/2015/05/11/phoenixauthentication/

SerialPort and Sleep Mruby Gems to Instruct Texas LaunchPad TM4C123G With ARM Cortex M4

| Comments

I always wanted to build something with mruby. After building mruby on my Raspberry Pi, I wanted to use the serialport mrbgem to instruct my Texas TM4C123G with ARM Cortex M4. I used to program the controller using Keil IDE on windows. After getting a mac, I have been writing program into it using energia. It is as simple as programming an arduino. The pin diagram with numbers are in the figure for the use in energia.

It has a built in led connected to the pins 1, 2, 3 and 4 of Port F (PF1, PF2, PF3, PF4). Each one contributes a single unique color to the led. So, when we give power to more than one of these pins, we get different colors. It’s fun working with these colors. So I have been using a serial communication program in the board so that it glows different leds with different combinations of PF1, PF2, PF3 and PF4.

The code is here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
 
  
  pinMode(30, OUTPUT);
  pinMode(40, OUTPUT);
  pinMode(39, OUTPUT);
  pinMode(31, OUTPUT);
  digitalWrite(40, HIGH);
}

void got_char(char x) {
 
  //if we get l over Serial and so on 
  if(x == 'l') {
    //... blink the LED
    digitalWrite(31,LOW);
    digitalWrite(40,HIGH);
    digitalWrite(39,LOW);
    digitalWrite(30,HIGH);
  }
  if(x == 'r'){
    digitalWrite(31,HIGH);
    digitalWrite(40,LOW);
    digitalWrite(39,HIGH);
    digitalWrite(30,LOW);
    
  }
  if(x == 'b'){
   digitalWrite(31,LOW);
    digitalWrite(40,HIGH);
    digitalWrite(39,HIGH);
    digitalWrite(30,LOW);
  }
  if(x == 'f'){
    digitalWrite(31,HIGH);
    digitalWrite(40,LOW);
    digitalWrite(39,LOW);
    digitalWrite(30,HIGH);
  }
  if(x == 's'){
    digitalWrite(31,LOW);
    digitalWrite(40,LOW);
    digitalWrite(39,LOW);
    digitalWrite(30,LOW);
  }
}
void loop()
{
  if(Serial.available() > 0) {
    //if there is, we read it
    byte byte_read = Serial.read();
 
    //and call "got_char"
    got_char((char)byte_read);
  }
  
}

After this, I went for mruby to play with the serialport mrbgem to instruct the controller. For this we have to install mruby first by following commands.

git clone http://github.com/mruby/mruby.git
cd mruby
make 

Then we have to add the path variable to .bashprofile file in the home of Raspberry Pi. Just add the line at the end of .bashprofile file.

export PATH=$PATH:/home/pi/mruby/bin/

Then after restarting the terminal, we can have all the necessary command line tools for mruby as mirb, mruby, mrbc. Let’s install the serialport and sleep mrbgems. First of all we need to install mgem (command line utility for mrbgems).

gem install mgem

Now, we need to add mruby-serialport and mruby-sleep to the known mrbgems.

mgem add mruby-serialport
mgem add mruby-sleep

Then we need to generate our content of build_config.rb in the root folder.

mgem config

Right after this command, we need to give inputs to the required field and after that it will generate the content of buildconfig.rb. Then just create a file called buildconfig.rb and paste the content generated into it. Like my build_config.rb looks like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
############################
# Start of your build_config

MRuby::Build.new do |conf|
  toolchain :gcc

  conf.bins = %w(mrbc)

  # mruby's Core GEMs
  conf.gem 'mrbgems/mruby-bin-mirb'
  conf.gem 'mrbgems/mruby-bin-mruby'
  conf.gem 'mrbgems/mruby-array-ext'
  conf.gem 'mrbgems/mruby-enum-ext'
  conf.gem 'mrbgems/mruby-eval'
  conf.gem 'mrbgems/mruby-exit'
  conf.gem 'mrbgems/mruby-fiber'
  conf.gem 'mrbgems/mruby-hash-ext'
  conf.gem 'mrbgems/mruby-math'
  conf.gem 'mrbgems/mruby-numeric-ext'
  conf.gem 'mrbgems/mruby-object-ext'
  conf.gem 'mrbgems/mruby-objectspace'
  conf.gem 'mrbgems/mruby-print'
  conf.gem 'mrbgems/mruby-proc-ext'
  conf.gem 'mrbgems/mruby-random'
  conf.gem 'mrbgems/mruby-range-ext'
  conf.gem 'mrbgems/mruby-sprintf'
  conf.gem 'mrbgems/mruby-string-ext'
#  conf.gem 'mrbgems/mruby-string-utf8'
  conf.gem 'mrbgems/mruby-struct'
  conf.gem 'mrbgems/mruby-symbol-ext'
  conf.gem 'mrbgems/mruby-time'
  conf.gem 'mrbgems/mruby-toplevel-ext'

  # user-defined GEMs
  conf.gem :git => 'https://github.com/monami-ya-mrb/mruby-serialport.git'
  conf.gem :git => 'https://github.com/matsumoto-r/mruby-sleep.git'
end

# End of your build_config
############################

I have commented the mruby-string-utf8 as it created some problems while installing. Then to build this in the directory, just hit rake.

rake

Then it will download the mebgems from git and will build it in the build directory. Before building, there are a few changes to be made in the mrbgems files. I found answers to my queries from the github repo of mruby-serialport. Just have a look here and set everything accordingly. After that use rake to build everyhting.

If it gets successful, we can write program (serialport.rb) to instruct our controller.

From a Ruby File

1
2
3
4
5
6
7
8
9
10
11
 sp = SerialPort.new("/dev/ttyUSB0", 9600, 8, 1, 0)
 sp.read_timeout=1000


list = ['f', 'b', 'r', 'l', 's']
loop do 
   list.each do |l|
     sp.write(l)
     Sleep::sleep(2)
   end
end

Provided you own the serialport file ttyUSB0 for the controller. Otherwise, do this.

sudo chown pi /dev/ttyUSB0

I am sending the characters from the list because I have programmed my board to receive these characters to glow certain leds. The Sleep::sleep(2) adds a delay of 2 seconds between consecutive writes of characters. To run this use the following.

mruby serialport.rb

And enjoy different colors glowing on the same led with a halt of 2 seconds.

From an Executable made using a C file

Then I wanted to run it with an executable built using the tool mrbc.

mrbc -Bserialport serialport.rb

It will create a file called serialport.c with an array called serialport[]. Just add the following at the end o f the serialport.c file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include "mruby.h"
#include "mruby/irep.h"
#include "mruby/proc.h"


int main(void) {

  mrb_state *mrb;
  mrb = mrb_open();

  mrb_load_irep(mrb, serialport);

  mrb_close(mrb);

  return 0;
}

After this run the following commands to make an executable.

gcc -I/home/pi/mruby/src -I/home/pi/mruby/include -c serialport.c -o serialport.o
gcc -o serialport serialport.o -lm /home/pi/mruby/build/host/lib/libmruby.a

The above command creates an executable serialport. Just run it and it will do the same that the ruby code was doing before.

Happy Hacking. :)

P.S. - make sure the baud_rate from both the sides are same. :P

Best Practices to Recover Ruby Gems and Developer Tools in Mac OSX El Capitan

| Comments

El Capitan has Darwin-15 (different from the last kernel). The first step that I found is to disable SIP (System Integrity Protection) by the following the steps below.

1. Rebooting in recovery mode by long pressing command + R on reboot
2. Accessing the terminal by going to utilities 
3. run the following in the terminal 

csrutil disable

Homebrew requires access to the path /usr/local. So we need to have access to this path by using the following commands.

sudo chflags norestricted /usr/local && sudo chown $(whoami):admin /usr/local && sudo chown -R $(whoami):admin /usr/local

After all these, it’s the best practice to update xcode to version 7.1 and install the command line tools as well. There are a lot of ways to do this.

Run the following in the terminal

xcode-select --install

If the above way fails, just click on xcode application and go to xcode -> Open Developer Tool -> More Developer Tools. It will take to you to the apple developer site. Just login there and according to the OS and Xcode version you have, download the command line tools file with the .dmg extension and install it.

Or else, the best way is to click on the mac app store and check for updates. There must be an update to install the command line tools and after that it’s done.

Fixing Gem native extension

I have a blog configured with Octopress and after updating the system to 10.11, bundle install always failed. With the command line tools installed and with proper permissions set to /usr/local/, I got the error while running

bundle exec rake preview

Error was

Starting to watch source with Jekyll and Compass. Starting Rack on port 4000
rake aborted!
Errno::ENOENT: No such file or directory - compass
/Users/user/git/octopress/Rakefile:85:in spawn
/Users/user/git/octopress/Rakefile:85:in block in <top (required)>
Tasks: TOP => preview

To have this removed, I prefered installing ruby from rbenv. Before that I have been using the system ruby. With rbenv, we can have the flexibity of having different versions of ruby installed for different projects. With the above fixes, homebrew must be working as usual.

brew update
brew install rbenv ruby-build

Ruby-build is an additional dependency for rbenv. After that we need to set the path so that we can have the command line utility of rbenv.

echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
source ~/.bash_profile

The above instruction adds a PATH variable to the .bash_profile to have the utility.

Then we need to install ruby from rbenv and to have a version of our choice globally. I preferred 2.2.3.

rbenv install 2.2.3
rbenv global 2.2.3

Now if we check

ruby -v 
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin15]

Now I wanted to have this version installed locally in my octopress blog. I just entered into it and ran the following.

rbenv rehash
rbenv local 2.2.3

Then I installed all the necessary gems by

bundle install 

But I eneded up with some errors that uses some versions specific issues. My Gemfile looked like this before.

cat Gemfile
source "https://rubygems.org"

group :development do
  gem 'rake', '~> 10.0'
  gem 'jekyll', '~> 2.0'
  gem 'octopress-hooks', '~> 2.2'
  gem 'octopress-date-format', '~> 2.0'
  gem 'jekyll-sitemap'
  gem 'rdiscount', '~> 2.0'
  gem 'RedCloth', '~> 4.2.9'
  gem 'haml', '~> 4.0'
  gem 'compass', '~> 1.0.1'
  gem 'sass-globbing', '~> 1.0.0'
  gem 'rb-fsevent', '~> 0.9'
  gem 'stringex', '~> 1.4.0'
  gem 'therubyracer'
end

gem 'sinatra', '~> 1.4.2'

Then I just removed the versions from the right side of each gem.

cat Gemfile 
source "https://rubygems.org"

group :development do
  gem 'rake'
  gem 'jekyll'
  gem 'rdiscount'
  gem 'therubyracer'
  gem 'pygments.rb'
  gem 'RedCloth'
  gem 'haml'
  gem 'compass'
  gem 'sass'
  gem 'sass-globbing'
  gem 'rubypants'
  gem 'rb-fsevent'
  gem 'stringex'
  gem 'liquid'
  gem 'directory_watcher'
  gem 'json'
end

Then I removed Gemfile.lock file to install gems locally from scratch again.

rm Gemfile.lock
gem pristine --all 
bundle install

Now :

bundle exec rake preview
Starting to watch source with Jekyll and Compass. Starting Rack on port 4000
/Users/tworit/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/liquid-2.3.0/lib/liquid/htmltags.rb:44: warning: duplicated key at line 47 ignored: "index0"
[2015-11-20 13:45:50] INFO  WEBrick 1.3.1
[2015-11-20 13:45:50] INFO  ruby 2.2.3 (2015-08-18) [x86_64-darwin15]
[2015-11-20 13:45:50] INFO  WEBrick::HTTPServer#start: pid=82642 port=4000
Configuration from /Users/tworit/tworitdash.github.io/_config.yml
Auto-regenerating enabled: source -> public
[2015-11-20 13:45:50] regeneration: 150 files changed
>>> Change detected at 13:45:51 to: screen.scss
identical public/stylesheets/screen.css 
>>> Compass is watching for changes. Press Ctrl-C to Stop.

Now, everything should work fine. :) Happy Hacking !

Compiling Anything From the Portstree Failed in FreeBSD 10.1 Raspberry Pi

| Comments

After getting portsnap extracted on my FreeBSD RPi Desktop, I wanted to compile a couple of things from the ports tree. But when I wanted to compile something, It first used to fetch “pkg” and the make failed. When I ran:

# pkg updtae

It first used to ask to install the package manager. Then it used to terminate and instruct to install pkg from /usr/ports/ports-mgmt/pkg . But that procedure also failed with the same error messages that I had got while compiling nano nad links from ports tree. I found out a simple but effective solution to this.

# whereis portmaster
portmaster: /usr/ports/ports-mgmt/portmaster/
# cd /usr/ports/ports-mgmt/portmaster && make install clean

Compiling portmaster was very time taking but it solved the issue and the pkg was successfully installed. Unfortunately I found no packagesite repositiry for “pkg update” online for FreeBSD:10.1:armv6 Release for Raspberry Pi. So, I couldn’t use the pkg tool to install packages. And I tried to compile packages from the ports tree by hand. The processor and RAM of Raspberry Pi cause problem while compiling. It even takes one whole day or more than that to compile a package from the ports tree.

Raspberry Pi FreeBSD Portsnap Fetch Clockktime Error

| Comments

After setting up the network, let’s try to fetch and extract the portsnap. Hell !! It resulted in something irritating.

# portsnap fetch
Looking up portsnap.FreeBSD.org mirrors... 2 mirrors found.
Fetching snapshot tag from portsnap1.FreeBSD.org... done.
Snapshot appears to have been created more than one day into the future!
(Is the system clock correct?)
Cowardly refusing to proceed any further.

This can be solved by using the proper timezone.

vi /etc/rc.conf 

And add the following:

ntpdate_enable="YES"

Then set up your timezone by the following command:

# tzsetup

Then after a reboot, the fetch will work. :)

# portsnap fetch extract

Configuring WiFi Adapter in FreeBSD Raspberry Pi

| Comments

After banging my head a lot of times, finally I found out the solution for connecting my Raspberry Pi to my WiFi network using an adapter. The adapter is from NetGear (realtek RTL IEEE 802.11) and while my machine used to boot up, it was recognized as “urtwn0” WiFi card. At first, the adopter didn’t glow. Then I found out that is a problem adapter. So, I had to allow the license for realtek urtwn0 driver in /boot/loader.conf file. The file didn’t exist and I created one.

vi /boot/loader.conf

Then write the following lines into it.

legal.realtek.license_ack=1
if_urtwn_load="YES"

I know editing the FreeBSD files using vi is a pain. You can use ee editor also. If you have connected the Pi before with some wired network and installed nano in it, you can also use the nano editor to edit. It is pretty smooth. Then, reboot your system.

reboot

After a reboot we are ready to create a network interface using wlan0.

ifconfig

It will show the listed cards with the IPs assigned to them. You can find no inet address for “urtwn0” driver.

ifconfig wlan0 create wlandev urtwn0

It will create an interface wlan0 and the command will return the ethernet address. If you are getting the address without any error, you are ready to go. To permanently store the configuration, we have to add some line to /etc/rc.conf .

vi /etc/rc.conf

The lines to be added are:

wlans_urtwn0="wlan0"
ifconfig_wlan0="WPA DHCP"

If you are having some difficulties while deleting characters in vi, just use ESC then d then left arrow button. Accordingly you can get how to delete multiple characters. Then ESC and i can help you edit the file again.

Then to get to know about the list of WiFi networks:

ifconfig wlan0 up scan

To connect to your network, you should edit the following file.

vi /etc/wpa_supplicant.conf

And write the following lines as per your WiFi SSID and Password.

network={
    ssid="your_ssid"
    psk="your_password"
}

Then after a reboot, you can see the adapter glowing and you can check the IP by ifconfig.

Checking your network is also easy. Just look at the content of your resolv.conf file.

cat /etc/resolv.conf

Then ping it. Like in my case:

ping 192.168.43.1

And you will get 0% packet loss after terminating.

Happy Hacking ! :)

Installing FreeBSD in Raspberry Pi With the Help of a Mac

| Comments

I have a Raspberry Pi B+ model. After running FreeBSD for about a month in the VirtualBox application in my Macbook Pro, I wished to have it installed natively somewhere else. Then I thought not to use a huge system or computer. I just needed a few space to run a server in a jail. Then, I happened to notice that my Raspberry Pi had not been used for ages. I had further plans to have a RFID security system using FreeBSD jails to configure the server to use it as a IoT (Internet of Things) project. Then, I arranged a HDMI cable, a USB keyboard, a 16 GB SD card from Samsung and a USB WiFi module (Netgear Adaptor).

So, let’s get started.

First connect the SD card to mac. Then open up the terminal and type

df -h

or

diskutil list

From the above commands, you can see your SD card volume as /dev/diskn. Where n is 2, 3 or something of that sort. And from the first command u can see a partition of that same as /dev/diskns1 or something like that. Now, we need to unmount that partition to start loading the image.

sudo diskutil umount /dev/diskns1

After getting the unmounted message, download the FreeBSD archive required for Raspberry Pi from the FreeBSD website. I downloaded it from here , from the ftp site. Then, double click on that archive to get the image file of the OS. Let it be in the Downloads folder. Then,

cd ~/Downloads
sudo dd if=your_image_file.img of=/dev/rdiskn bs=1m

It will take sometime to write the image on to the SD card. Before running this command, do know what it means. “if” stands for input file. “of” stands for output file. And make sure to write rdiskn instead of diskn. This will write the image in a raw disk format and the process will be faster. And, the other difference that I have marked is that, if one is using diskn in stead of rdiskn, after writing the disk space created will not be visible. If you insert it again, you will find a message of incompatibility. Then you will end up formatting your disk once again. And make sure that diskn is really your SD card. Otherwise, you will end up destroying your mac.

After writing the image, you can see the disk space in finder. Click on it to see inside. Then a few things need to be replaced in the disk. The bootcode.bin and the start.elf need to be replaced. Go here to find the the above mentioned files and replace them in the disk.

Then eject the SD card and put in your Pi. Connect the HDMI cable to the Pi and to a monitor. Connect a USB keyboard as well. Then power up your Pi.

Voila !! It’s working.

P.S. - If it doesn’t work, go to the firmware github page once again and fetch all the fixup and start files and replace them in the disk (SD card) and don’t destroy your mac. It’s pretty expensive. :P

Monngo DB in Fedora

| Comments

It is somewhat difficult to run mongo db by following the conventional steps for installing it in fedora. While starting mongo db, the normal problem that is usually encountered after authenticating is

$ systemctl start mongod

$ starting mongod (via systemctl):  Job failed. See system journal and 'systemctl status' for details.  [FAILED]

And it is usualy found that the mongod.log is empty or rather absent. If one of the commands mongo or mongod is not working, then also the installation is incomplete becasue the mongo db server satrts with mongod and, if it is not working properly, it will be difficult to connect mongo clients to it even after providing correct authentication for the user.

It is also usually seen that the command /usr/bin/mongod or the archive /usr/share/man/man1/mongod.1.gz is not present.

Installing Mongo DB in Fedora

First we have to remove the installed versions (if there is any).

$ sudo su
# yum erase mongodb
# yum erase mongo-10gen
# yum --disablerepo= * --enablerepo=fedora,updates install mongodb mongodb-server

Running Mongo

# systemctl start mongod.service

Verifying

# systemctl status mongod.service
# tail /var/log/mongodb/mongodb.log
# nmap -p27017 localhost

Because the default port for mongo db is 27017.

Running mongo clinet

#mongo

Starting mongo db each time you boot.

#systemctl enable mongod.service

Happy Hacking. :)