Sunday, December 11, 2016

Bright your LED with Raspberry PI


In Last blog i setup Raspberry PI, Initially i planned to not write blog for this example as internet already provided lot of examples and tutorial for flashing LED with Raspberry PI. but during my experience to test with PI4J i tried to explain things in my way.

This will be step by step tutorial starting with connecting the cables then some explanations and writing code in PI4J.

The Raspberry Pi is single board computer which is very good for prototyping and it has 40 pins that can be configured for General Purpose I/O (GPIO) and more.

First fit T-shaped Cobbler breakout board via a ribbon cable on breadboard. This is easier and safer than working directly on Raspberry Pi.(Like showed in Pic on left side)

Pin Numbering
Due to Pin numbering issue i was not able to run my sample at first so i have to learn more.
Pi4J is based on a project called WiringPi, which is a set of native libraries that provide access to the RPi’s GPIO ports. The labeled name on cobbler is different then the name used by PI4J, The pin numbers and their mapping to the actual pins on the RPi header are given in the picture below. So refer below for running for your samples.
For basic concept i will recommend following link

Breadboard
The breadboard is a way of connecting electronic components to each other without having to solder them together. They are often used to test a circuit design before creating a Printed Circuit Board (PCB).
The holes on the breadboard are connected in a pattern.
LED
When you pick up the LED, you will notice that one leg is longer than the other. The longer leg (known as the ‘anode’), is always connected to the positive supply of the circuit. The shorter leg (known as the ‘cathode’) is connected to the negative side of the power supply, known as ‘ground’.
Resistor
You must ALWAYS use resistors to connect LEDs up to the GPIO pins of the Raspberry Pi. The Raspberry Pi can only supply a small current (about 60mA). The LEDs will want to draw more, and if allowed to they will burn out the Raspberry Pi. Therefore putting the resistors in the circuit will ensure that only this small current will flow and the Pi will not be damaged.

Building Circuit
The circuit consists of a power supply (the Pi), an LED that lights when the power is applied, and a resistor to limit the current that can flow through the circuit.
You will be using one of the ‘ground’ (GND) pins to act like the ‘negative’ or 0 volt ends of a battery. The ‘positive’ end of the battery will be provided by a GPIO pin. 
GPIO pin 0 --> Jumper one leg
Jumper Second leg --> long leg of LED(same column)
Short leg of LED --> 330Ω resistor --> Ground.

Find below picture



Now you can run pi4j example, follow below link


Raspberry PI setup in Headless Mode


Today i received my Raspberry PI 3 ultimate kit, The Raspberry Pi (RPi) is a single board computer based on the Broadcom BCM2835 System on Chip (SoC) it comes equipped with a General Purpose Input/Output (GPIO) connector, that can be used for connecting peripherals such as sensor, LEDs, motors etc.
 
I dont have monitor and keyboard to make it workable for me as i only have MAC laptop, After searching and reading different blogs and lot of different tries and failures following are steps which make my Raspberry PI accessible from my MAC without using any cable. Only requirement is you should have WiFi LAN, mostly we have for Internet connectivity

Unbox kit and assemble Raspberry PI as per Quick start guide provided by Vilros.

The microSD card that comes with kit already contains NOOBS(New Out of Box Software), When Pi will start and load the NOOBS tool, you can install Raspbian(its Linux distribution based on Debian, another popular version of linux) using NOOBS GUI.

To perform above steps we need Monitor and Keybooard but as we don't have so its recommended to prepare your MicroSD card using steps mentioned on this link http://elinux.org/RPi_Easy_SD_Card_Setup

So just put Card in your laptop Card reader and follow steps mentioned on above link. Keep card in card reader and do following configurations

edit following configuration on your card like

vi /etc/wpa_supplicant/wpa_supplicant.conf

add below line make sure values are in quotes don't remove it
network={
    ssid="wifi user name"
    psk="wifi network password"
}
To insert SD card, Make sure raspberry power is off and locate SD Card socket under side of Pi's board. Push SD card gently in socket.

Now when you Power On your PI you would be able to SSH but how to get IP of raspberry PI?

In my CISCO routers its like
status --> local network --> DHCP Client Table

I can see raspberrypi IP.

Now simply from the Laptop which is connected on same router just do

ssh pi@

and now Raspberry PI is in your control. :)

You can configure VNC Server if you still want to access raspberry PI in desktop environment.

To configure VNC Server from command line of same ssh do following

pi@raspberry:/ sudo raspi-config

Your command prompt would be like


Navigate to Advanced Options
scroll down and select VNC and select Yes

Then run vncserver, Make note of the IP Address/display number like 192.168.1.6:1

Now from your laptop use VNC Viewer and provide above mentioned info. You Can access Raspberry PI in GUI mode.

Friday, October 2, 2015

MMS with Apache Camel

Following is the sample code to send MultiMedia message to MMSc over MM7 protocol

public class MmsRouter extends RouteBuilder {

     public void configure() {
        from("timer:foo?period=5m")
        .process(    new MmsPreProcessor()      )
        .to("http://x.x.x.x/vasp/servlet/messagerouter");
    }

}

public class MmsPreProcessor implements Processor {

       @Override
       public void process(Exchange exchange) throws Exception {

              MessageFactory factory = MessageFactory.newInstance();
              SOAPMessage soapMeassage = factory.createMessage();

              SOAPEnvelope envelope = soapMeassage.getSOAPPart().getEnvelope();
           
              SOAPHeader header = envelope.getHeader();
              SOAPBody body = envelope.getBody();

              SOAPFactory soapFactory = SOAPFactory.newInstance();

              //Header
              Name headerName = soapFactory.createName("TransactionID", "mm7", "http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4");

              SOAPHeaderElement headerElement = header.addHeaderElement(headerName);
              headerElement.setTextContent("TID.1234567");
              headerElement.setMustUnderstand(true);
           
              //Soap message body
              Name submitReqName = soapFactory.createName("SubmitReq");
              SOAPBodyElement submitReq = body.addBodyElement( submitReqName );
         
              SOAPElement MM7Version =  submitReq.addChildElement(  soapFactory.createName("MM7Version") );
              MM7Version.setTextContent("6.8.0");

              //SO senderIdentification
              SOAPElement senderIdentification =  submitReq.addChildElement( soapFactory.createName("SenderIdentification") );
           
              SOAPElement vaspID =  senderIdentification.addChildElement( soapFactory.createName("VASPID") );
              vaspID.setTextContent("vaspid");
              SOAPElement vasID =  senderIdentification.addChildElement( soapFactory.createName("VASID") );
              vasID.setTextContent("1234");

              SOAPElement senderAddress =  senderIdentification.addChildElement( soapFactory.createName("SenderAddress") );
              SOAPElement shortCode =  senderAddress.addChildElement( soapFactory.createName("Number") );
              shortCode.setTextContent("9394");

              SOAPElement recipients =  submitReq.addChildElement( soapFactory.createName("Recipients") );
              SOAPElement to =  recipients.addChildElement( soapFactory.createName("To") );
              SOAPElement number =  to.addChildElement( soapFactory.createName("Number") );
              number.setTextContent("+9xxxxxxxxx");

              SOAPElement messageClass =  submitReq.addChildElement( soapFactory.createName("MessageClass") );
              messageClass.setTextContent("Auto");

              SOAPElement subject =  submitReq.addChildElement( soapFactory.createName("Subject") );
              subject.setTextContent("Hello World");
           
              Name contentName = soapFactory.createName("Content");
              SOAPElement contentElement =  submitReq.addChildElement( contentName );
              contentElement.addAttribute(envelope.createName("href"), "cid:mm7-content");
              contentElement.addAttribute(envelope.createName("allowAdaptations"), "false");
           
              DataHandler dataHandler = new DataHandler(  new URL("file:///abc.jpg")   );
              AttachmentPart imgAttachment = soapMeassage.createAttachmentPart( dataHandler );
              imgAttachment.setContentId("mms-content-img");

              soapMeassage.addAttachmentPart( imgAttachment );

              exchange.getOut().setHeader(Exchange.HTTP_METHOD,"POST");

 Iterator it = soapMeassage.getMimeHeaders().getAllHeaders();
                 
              while (it.hasNext()) {
                   MimeHeader mimeHeader = (MimeHeader) it.next();
                   exchange.getOut().setHeader(mimeHeader.getName(),mimeHeader.getValue());
              }
                       
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              soapMeassage.writeTo(baos);

              exchange.getOut().setBody( baos );
           
       }

}

Any suggetions to improve above code are welcome.

Tuesday, July 8, 2014

Running Java Application with Solaris SMF as Non-Root User

Sample SMF manifes file

<?xml version='1.0'?>
<!DOCTYPE service_bundle SYSTEM '/usr/share/lib/xml/dtd/service_bundle.dtd.1'>
<service_bundle type="manifest" name="myapp">
         <service name="application/management/myapp" type="service" version="1">
                 
<!-- Initial state of the service is disabled -->
<create_default_instance enabled="false" />
 
<single_instance />
                 
<dependency name="multi-user-server" type="service" grouping="require_all" restart_on="none">
    <service_fmri value="svc:/milestone/multi-user-server" />
</dependency>
                 
<exec_method type="method" name="start"     exec="/opt/bin/myapp.sh start" timeout_seconds="-1">
    <method_context>
       <method_credential user='myuser' group='other' />
           <method_environment>
  <envvar name='PATH' value='/usr/bin:/usr/sbin:/usr/ccs/bin:/usr/local/bin:/usr/local/sbin:/usr/sfw/bin' />
  <envvar name='JAVA_HOME' value='/usr/java/' />
       </method_environment>
   </method_context>
</exec_method>
                          
<exec_method type="method" name="stop"      exec="/opt/bin/myapp.sh stop" timeout_seconds="-1">
  <method_context>
  <method_credential user='myuser' group='other' />
      <method_environment>
<envvar name='PATH' value='/usr/bin:/usr/sbin:/usr/ccs/bin:/usr/local/bin:/usr/local/sbin:/usr/sfw/bin' />
<envvar name='JAVA_HOME' value='/usr/java/' />
      </method_environment>
 </method_context>
 </exec_method>
                 
<property_group name='start' type='method'>
<propval name='action_authorization' type='astring' value='solaris.smf.manage.myapp' />
<propval name='modify_authorization' type='astring' value='solaris.smf.manage.myapp' />
<propval name='value_authorization'  type='astring'  value='solaris.smf.manage.myapp' />
</property_group>
<property_group name='stop' type='method'>
<propval name='action_authorization' type='astring' value='solaris.smf.manage.myapp' />
<propval name='modify_authorization' type='astring' value='solaris.smf.manage.myapp' />
<propval name='value_authorization'  type='astring' value='solaris.smf.manage.myapp' />
</property_group>
<property_group name='general' type='framework'>
<propval name='action_authorization' type='astring' value='solaris.smf.manage.myapp' />
<propval name='value_authorization'  type='astring' value='solaris.smf.manage.myapp' />
<propval name='modify_authorization' type='astring' value='solaris.smf.manage.myapp' />
                  </property_group>
 
                 <stability value="Unstable" />
 
                 <template>
                          <common_name>
                                   <loctext xml:lang='C'>My Application</loctext>
                          </common_name>
                 </template>
         </service>
</service_bundle>

Now perform following steps from root users
  • svccfg validate myapp-smf.xml
  • Add line in /etc/security/auth_attr solaris.smf.manage.myapp:::MyApp Management::
  • usermod -A solaris.smf.manage.myapp myuser(make sure myuser is not logged in)
  • svccfg import /opt/smf/myapp-smf.xml
Now logged as myuser and verify/start/stop application with following commands
svcs -l myapp
svcadm enable myapp
svcadm disable myapp

Saturday, April 5, 2014

Parlay Rest SMS with Apache Camel

Following sample will use http4 Apache component to send Sms using Parlay Rest Specification

package com.test.rest.sms;

import org.apache.camel.main.Main;

public class TestRestSms {

public static void main(String[] args) throws Exception {
            Main main = new Main();
            main.enableHangupSupport();
            main.addRouteBuilder(new TestRestSmsRoute());
            System.out.println("Starting Camel. Use ctrl + c to terminate the JVM.\n");
            main.run();
}
}

Following is RouterClass

import org.apache.camel.builder.RouteBuilder;

public class TestRestSmsRoute extends RouteBuilder {

@Override
public void configure() throws Exception {

from("timer://foo?delay=0&period=20000")
.process(new SendSmsRequest())
.to("http4://172.21.7.1:5001/rest/sms/messages")
.process(new SendSmsResponse())
}

}

Following are processor classes

import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Message;
import org.apache.camel.Processor;

public class SendSmsRequest implements Processor  {

@Override
public void process(Exchange exchange) throws Exception {

exchange.getIn().setHeader(Exchange.HTTP_METHOD, "POST");
exchange.getIn().setHeader(Exchange.CONTENT_TYPE,"application/json");
   
String toAddress = "\"addresses\": [\"tel:6666666666\"]";
String fromAddress = "\"senderName\": \"tel:321\"";
String msgText = "\"message\": \"hello world\"";
        String sms                 = "{"+toAddress+","+fromAddress+","+msgText+"}";

        exchange.getIn().setBody(sms);

} //

}

public class SendSmsResponse implements Processor  {

@Override
public void process(Exchange exchange) throws Exception {

Object result = exchange.getIn().getBody();

System.out.println("sms response="+result);

}

}

How to Send SMS with Parlay Rest

OMA provide specification for communication with telecom nodes, one of them is parlay rest to send sms.

Following is java sample to send sms following Parlay Rest specification

package com.test.rest.sms;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class RestSms {

Private URL sendSmsUrl = new URL("http://192.168.0.1:8080/rest/sms/messages");

public void sendSms() {

try {
HttpURLConnection connection =   (HttpURLConnection)sendSmsUrl.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
        connection.connect();
//For simplicity we write JSON String format, we can use any library for this

String toAddress = "\"addresses\": [\"tel:666666666\"]";
String fromAddress = "\"senderName\": \"tel:321\"";
String msg Text = "\"message\": \"hello world\"";
String sms                 = "{"+toAddress+","+fromAddress+","+msgText+"}";

OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write( sms );
wr.flush();

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
    while ((line = rd.readLine()) != null) {
        // Process line... and output response code
    }
    wr.close();
    rd.close();
                        
    connection.disconnect();
                        
        } catch (Exception e) {
e.printStackTrace();
        }//EO try-catch
   }

}

Wednesday, September 11, 2013

Hello World With Maven in Eclipse IDE

We will develop Hello World app, without using Maven Console based commands,

Please follow the below steps.
1. Download Eclipse IDE for Java EE Developers, this contain all preconfigured Maven Plugin, you dont have to waste time in extra configurations.

2.  In Eclipse open the New Project Wizard by clicking File --> New --> Project. Under 'Maven' select 'Maven Project' and click 'Next'

3. On the next page of wizard, check 'Create a simple project' and click 'Next'



4. On the next Page of Wizard, Give a 'Group Id' and an 'Artifact Id' and click 'Finish'.

5.  Create a class with a main method in src/main/java. In this case I created Main.java



6. In the main method we will print out message and our project look like 



7. Now we have to deploy our project, our created pom.xml is not ready to deploy our application properly. Through the pom file we can instruct Maven about how to deploy our project, such as which class is the main class. We have to add following entries in pom.xml.




8. Remember, whenever you do manual changes in pom.xml you have to Run Maven->Update Project.



9. Now we will build project with Maven, If we right-click on the pom.xml file and select Run As menu, we will see a list of options as shown in the following figure.


If you select the Maven install option, Maven will compile and test our code and if all goes well it creates the JAR file in the target directory. The Maven clean option will empty the target directory and the Maven test will simply run the test cases.

10. Now run jar file and you will see