Thursday, 7 December 2017




SERVER SETUP FOR UBUNTU SYSTEM WITH PASSENGER AND APACHE (DEPLOY RAILS APP WITH MYSQL, APACHE UBUNTU 16.04 WITH GOOGLE CLOUD PLATFORM FOR BEGINNERS)

  1. First of all, we have to buy a server with some service providers (ex: google cloud platform, AWS, digital ocean etc,.)
  2. for a beginner go for any free server like google cloud platform (free for one year) 
  3. then set up the server for rails things
  4. get into the server with ssh key,.
update and upgrade your server:

sudo apt-get update
sudo apt-get upgrade

Step 1 — Installing Apache

sudo apt-get install apache2

Step 2 — Install Passenger

First, install the PGP key for the repository server:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 561F9B9CAC40B2F7

sudo nano /etc/apt/sources.list.d/passenger.list
Insert the following line to add the Passenger repository to the file:
deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main

Step 3 — Installing RVM and Ruby

We won't be installing Ruby directly. Instead, we'll use a Ruby Version Manager. There are lots of them to choose from (rbenv, chruby, etc.), but we'll use RVM for this tutorial. RVM allows you to easily install and manage multiple rubies on the same system and use the correct one according to your app. This makes life much easier when you have to upgrade your Rails app to use a newer ruby.
Before installing RVM, you need to import the RVM GPG Key:
  • gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
Then install RVM to manage our Rubies:
  • curl -sSL https://get.rvm.io | bash -s stable
This command uses curl to download the RVM Installation script from https://get.rvm.io. The -sSL option is composed of three flags:
  • -s tells curl to download the file in 'silent mode'
  • -S tells curl to show an error message if it fails
  • -L tells curl to follow all HTTP redirects while retrieving the installation script
Once downloaded, the script is piped to bash. The -s option passes stable as an argument to the RVM Installation script to download and install the stable release of RVM.
Note: If the second command fails with the message "GPG signature verification failed", that means the GPG Key has changed, simply copy the command from the error output and run it to download the signatures. Then run the curl command for the RVM Installation.
We need to load the RVM script (as a function) so we can start using it. We then need to run the requirements command to automatically install required dependencies and files for RVM and Ruby to function properly:
  • source ~/.rvm/scripts/rvm
  • rvm requirements
We can now install the Ruby of our choice. We'll be installing the latest Ruby 2.2.1 (at the time of writing) as our default Ruby:
  • rvm install 2.2.1
  • rvm use 2.2.1 --default

Step 4 — Installing Rails and Bundler

Once Ruby is set up, we can start installing Rubygems. We'll start by installing the Rails gem that will allow your Rails application to run, and then we'll install bundler which can read your app's Gemfile and automatically install all required gems.
To install Rails and Bundler:
  • gem install rails -V --no-ri --no-rdoc
  • gem install bundler -V --no-ri --no-rdoc
Three flags were used:
  • -V (Verbose Output): Prints detailed information about Gem installation
  • --no-ri - (Skips Ri Documentation): Doesn't install Ri Docs, saving space and making installation fast
  • --no-rdoc - (Skips RDocs): Doesn't install RDocs, saving space and speeding up installation

Note: You can also install a specific version of Rails according to your requirements by using the -v flag:
  • gem install rails -v '4.2.0' -V --no-ri --no-rdoc
In my server rails version is 5.1.4, ruby version is 2.4.1p111 (please use this for no dependency error )


Setting up your production database is pretty easy. Make sure to keep in mind that you should use a different password for your production databases.
Depending on what database you want to use, follow the steps related to the database:

Installing MySQL

All you need to do in order to install MySQL is to run the following command:
sudo apt-get install mysql-server mysql-client libmysqlclient-dev
You can use the root user and password set during installation for your database or you can add a new user to MySQL.
Make sure you also create your app's database now. If you're not sure how to do this, follow this guide to create your mysql database. Take note of your database name and password so you can use this when we setup the database.yml file later on.

Installing PostgreSQL

Postgres 9.3 is available in the Ubuntu repositories and we can install it like so:
sudo apt-get install postgresql postgresql-contrib libpq-dev
Next, we need to setup our Postgres user (also named "deploy" but different from our Linux user named "deploy") and database:
sudo su - postgres
createuser --pwprompt deploy
createdb -O deploy my_app_name_production # change "my_app_name" to your app's name which we'll also use later on
exit
The password you type in here will be the one to put in your my_app/current/config/database.yml later when you deploy your app for the first time.
  • then the main part is get into this dir (cd /var/www)
  • git clone <app repo>
  • or create one file with rails new testapp -d mysql (for mysql instead of sqlite3)
  • then go inside the database.yml
# MySQL. Versions 5.1.10 and up are supported.
#
# Install the MySQL driver
#   gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
#   gem 'mysql2'
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.7/en/old-client.html
#
default: &default
  adapter: mysql2
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: root
  socket: /var/run/mysqld/mysqld.sock

development:
  <<: *default
  database: test_app_development

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: test_app_test

# As with config/secrets.yml, you never want to store sensitive information,
# like your database password, in your source code. If your source code is
# ever seen by anyone, they now have access to your database.
#
# Instead, provide the password as a unix environment variable when you boot
# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full rundown on how to provide these environment variables in a
# production deployment.
#
# On Heroku and other platform providers, you may have a full connection URL
# available as an environment variable. For example:
#
#   DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase"
#
# You can use this database configuration with:
#
#   production:
#     url: <%= ENV['DATABASE_URL'] %>
#
production:
  <<: *default
  database: test_app_production
  username: root
  password: root
configure the production part with your user name and password 
  • create the db and migrate with these commands
RAILS_ENV=production rake db:create
RAILS_ENV=production rake db:migrate
get into this dir cd /etc/apache2/sites-enabled/

this is the config file of the enable site apache=> do the following with your folder name
<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        ServerName {{ip}}
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/{{folder_name}}/public
        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        <Directory "/var/www/{{name}}">
        Options FollowSymLinks
        Require all granted
    </Directory>
        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>


Step 6 — Deploy
At this point you can deploy your own Rails application if you have one ready. If you want to deploy an existing app, you can upload your project to the server and skip to the /etc/apache2/sites-available/default step.
For this tutorial, we will create a new Rails app directly on the Droplet. We will need the rails gem to create the new app.
Move to your user's home directory:
cd ~
Install the rails gem without extra documentation, which makes the installation faster. This will still take a few minutes:
sudo gem install --no-rdoc --no-ri rails
Now we can create a new app. In our example, we will use the name testapp. If you want to use another name, make sure you update the paths in the other commands and files in this section.
We will skip the Bundler installation because we want to run it manually later.
rails new testapp --skip-bundle
Enter the directory:
cd testapp
Now we need to install a JavaScript execution environment. It can be installed as the therubyracer gem. To install it, first open the Gemfile:
nano Gemfile
Find the following line:
# gem 'therubyracer',  platforms: :ruby
Uncomment it:
gem 'therubyracer',  platforms: :ruby
Save the file, and run Bundler:
bundle install
Now, we need to create a virtual host file for our project. We'll do this by copying the default Apache virtual host:
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/testapp.conf
Open the config file:
sudo nano /etc/apache2/sites-available/testapp.conf
Edit it or replace the existing contents so your final result matches the file shown below. Changes you need to make are highlighted in red. Remember to use your own domain name, and the correct path to your Rails app:
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    ServerAdmin webmaster@localhost
    DocumentRoot /home/rails/testapp/public
    RailsEnv development
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    <Directory "/home/rails/testapp/public">
        Options FollowSymLinks
        Require all granted
    </Directory>
</VirtualHost>
Basically, this file enables listening to our domain name on port 80, sets an alias for the www subdomain, sets the mail address of our server administrator, sets the root directory for the public directory of our new project, and allows access to our site. You can learn more about Apache virtual hosts by following the link.
To test our setup, we want to see the Rails Welcome aboard page. However, this works only if the application is started in the development environment. Passenger starts the application in the production environment by default, so we need to change this with the RailsEnv option. If your app is ready for production you'll want to leave this setting out.
If you don't want to assign your domain to this app, you can skip the ServerName and ServerAliaslines, or use your IP address.
Save the file (CTRL+X, Y, ENTER).
Disable the default site, enable your new site, and restart Apache:
sudo a2dissite 000-default
sudo a2ensite testapp
sudo service apache2 restart
Now your app's website should be accessible. Navigate to your Droplet's domain or IP address:
http://droplet_ip_address
Verify that your app is deployed. You should see either your custom application, or the Welcome aboarddefault Rails page:
Test page
The Rails app is now live on your server.

Step 7 — Update Regularly

To update Ruby, you will need to compile the latest version as shown in Step 4 in this tutorial.
To update Passenger and Apache, you will need to run a basic system update:
sudo apt-get update && sudo apt-get upgrade
However, if there is a new system Ruby version available, it will probably overwrite our Ruby (installed from source). For this reason, you might need to re-run the commands for removing the existing symlink to the Ruby binary file and creating a new (correct) one. They are listed at the end of Step 6 in this tutorial.
After the update process, you will need to restart the web server:
sudo service apache2 restart

Sunday, 1 October 2017

Md inline input without directives in angular 2 or 2+ : 


hi here i have entered how to use inline input without directives =>

you just change the model name and value in the below code and use this thing and change the css also according to your code...

propertyName:  <span *ngIf='!propertyName_edit' (click)="propertyName_edit=true">{{propertyName}}<md-icon mdSuffix class="propertyName">mode_edit</md-icon></span>

 <input *ngIf='propertyName_edit' (keydown)="handleKeyDown_propertyName($event,i)" (focusout)="propertyName_edit=false" [value]="propertyName" autofocus/>



handleKeyDown_propertyName(event,i)
{
if (event.keyCode == 13)
{
this.test_value[i].propertyName=event.target.value;
this.propertyName_edit=false;
}
}

Saturday, 16 September 2017

HOW TO TAKE A VALUE FROM ARDUINO AND SEND IT TO THE INTERNET WITHOUT ETHERNET (THING SPEAK.COM) USING NODE JS IN UBUNTU:

First you need to download Arduino in your ubuntu to download arduino from ubuntu execute this line

sudo apt-get update && sudo apt-get install arduino arduino-core

For example i took ultrasonic sensor to generate the data you can take whatever you want






connection diagram for ultrasonic and arduino

connect pin 

vcc to arduino vcc 
ground to arduino ground
trigpin to arduino 9 th port
echo to arduino 10 th 

then exec following line of command using Arduino IDE

  1. /*
  2. * Ultrasonic Sensor HC-SR04 and Arduino Tutorial
  3. *
  4. * Crated by Dejan Nedelkovski,
  5. * www.HowToMechatronics.com
  6. *
  7. */
  8. // defines pins numbers
  9. const int trigPin = 9;
  10. const int echoPin = 10;
  11. // defines variables
  12. long duration;
  13. int distance;
  14. void setup() {
  15. pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  16. pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  17. Serial.begin(9600); // Starts the serial communication
  18. }
  19. void loop() {
  20. // Clears the trigPin
  21. digitalWrite(trigPin, LOW);
  22. delayMicroseconds(2);
  23. // Sets the trigPin on HIGH state for 10 micro seconds
  24. digitalWrite(trigPin, HIGH);
  25. delayMicroseconds(10);
  26. digitalWrite(trigPin, LOW);
  27. // Reads the echoPin, returns the sound wave travel time in microseconds
  28. duration = pulseIn(echoPin, HIGH);
  29. // Calculating the distance
  30. distance= duration*0.034/2;
  31. // Prints the distance on the Serial Monitor
  32. Serial.print("Distance: ");
  33. Serial.println(distance);
  34. }

Then it will produce the Serial out put You can see the out put using serial monitor in arduino IDE

NEXT STEP IOT:

Download node js in your ubuntu system...

it is very easy installation procedure:

Step 1: Add Nodejs PPA

Node.js is available in two versions, first is current (most recent version) and another is LTS. Select which version you need to install on the system. Then use one of following commands to install PPA on your system. Node.js officially provides these PPA’s.
Use Current Release: At te last update of this tutorial, Node.js 8.0 is the current Node.js release available.
$ sudo apt-get install python-software-properties
$ curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
Use LTS Release : At te last update of this tutorial, Node.js 6.11 is the LTS release available.
$ sudo apt-get install python-software-properties
$ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
For this tutorials, we are using latest current release and added their PPA to my system.

Step 2: Install Nodejs and NPM

After adding required PPA file lets install Node package. NPM will also be installed with node.js. This command will also install many other dependent packages on your system.
$ sudo apt-get install nodejs

Step 3: Check Node.js and NPM Version

After installing node.js verify and check the installed version. You can find more details about current version on node.js official website.
$ node -v 

v8.2.1
Also, check the version of installed npm.
$ npm -v 

5.3.0
thats all for installation about node js

after install node js if you want to look how the node js and all click here...

then you have add two things in your node js that is serialport , thingspeakclient 


Before going for node js we have to lok about thingspeak for post all our data and get our data ...
it will give you the free api to see our data in cloud... lets look at that


here you have to create one account ... then make one channel for post your data

click the new channel to create channel

then enter the label name for identification


then click save then your channel will be saved.

lets look at the api 



go to the Api-keys to see the api of your channel...

connect the arduino to your laptop using usb

then choose your port in arduino then copy the port name and paste here

var port = new SerialPort('/dev/ttyACM1', { autoOpen: false });   <-- this code is in node js 7th line

look at the write key and channel id for post the data you have to enter your channel id and write key instead of mine...

client.attachChannel(<channel id>, { writeKey:'<writekey>', readKey:'<readkey>'}, function(){

   if (i==1){
     console.log("connected!!!")
     i++;
   }
 });

client.updateChannel(<channel id>, {<channel field name>: buff}, function(err, resp) {
// console.log(resp)
    if (!err && resp > 0) {
        console.log('update successfully. Entry number was: ' + resp);
        console.log('value is: ' + buff);
    }
});


// client.getChannelFeeds(<channel id>,'<channel field name>', function(err, resp) {
//  console.log(resp)

//     if (!err && resp > 0) {
//         console.log('update successfully. Entry number was: ' + resp);
//     }
// });


you can see the channel id and write key and read from the same api-key page




Thats all we will see node js to post the data

create ultrasonic.js file in your desktop

var ThingSpeakClient = require('thingspeakclient');
var client = new ThingSpeakClient();

var request = require('request');
var http = require('http');
var http = null;
var SerialPort = require('serialport');
var port = new SerialPort('/dev/ttyACM1', { autoOpen: false });
i=1;
port.open(function (err) {
  if (err) {
    return console.log('Error opening port: ', err.message);
  }

  // Because there's no callback to write, write errors will be emitted on the port: 
  port.write('main screen turn on');
});

// The open event is always emitted 
port.on('open', function() {
  return console.log('Port opened');
  // open logic 
});
// Switches the port into "flowing mode" 
// port.on('data', function (data) {
//   console.log('Data:', data);
// });

// Read data that is available but keep the stream from entering "flowing mode" 
port.on('readable', function () {
  // console.log('Data:', port.read());
  var buff = new Buffer(port.read(), 'utf8'); //no sure about this
  // console.log('data received: ' + buff.toString());
  // debugger

  client.attachChannel(321131, { writeKey:'WNCHK5PZ0E6QLA11', readKey:'XMKWNQW2I7JQJGXS'}, function(){

   if (i==1){
     console.log("connected!!!")
     i++;
   }
 });


client.updateChannel(321131, {field1: buff}, function(err, resp) {
// console.log(resp)
    if (!err && resp > 0) {
        console.log('update successfully. Entry number was: ' + resp);
        console.log('value is: ' + buff);
    }
});


// client.getChannelFeeds(321131,'field1', function(err, resp) {
//  console.log(resp)

//     if (!err && resp > 0) {
//         console.log('update successfully. Entry number was: ' + resp);
//     }
// });


});

copy and paste this code in your ultrasonic.js 

to run the js execute this line node ultrasonic.js

each and every 15 second the api will get updated in thingspeak.com

here is the example data in thingspeak like this you will get datas


enjoy coding with electronic...