Monday, October 27, 2014

Port tunneling on Mac with SSH


Imagine you need to connect from your browser to another computer which has access to an specific service, por example a private control panel. How to do it using SSH on a mac?

Well, lets describe the problem:


I want to access to the Service 192.168.300.12:11801 which can be accesed only from the Server SSH 192.168.200.1. To increase the complexity of the problem, we should use HTTPS to access the Service, ie, the direct URL from Server SSH looks like: https://192.168.300.12:11801/index.html

Well, first we open a terminal and execute the command:

$ sudo ssh -L 443:192.168.300.12:11801 -p 22 -l username -N 192.168.200.1

The command opens a tunnel between our machine on port 443 to machine 192.168.300.12 using the port 11801 through 192.168.200.1. Just what we want. "-p  20" is only the SSH port, "-l username" is clear and "-N" indicates that we will not execute remove commands.

Now, we can simply set up a SOCKS-Proxy going to Mac > Installation > Network > More Options. Select the tab "Proxies" and enable the protocol SOCKS-Proxy. You need only to insert:
  • SOCKS-Proxy-Server: 127.0.0.1
  • Port: 443
Now, open your favorite browser and write the URL:
https://localhost/index.html
to access to the Service.

Hope help



How normalization between two numbers works


A friend asked me today about how to normalize a range into another one. Well, given a range from A to B we want to convert it to a scale of C to D, where A maps to C and b maps to D, and we want to do it with a linear function. For example, if C=1 and D=5, ie, interval [1,5], that means that A maps 1 and B maps 5.

The following linear equation does exactly what we need

f(x) = 1 + (x-A)*(5-1)/(B-A) 

because
f(A)=1 + (A-A)*(5-1)/(B-A) = 1+0 = 1 
and
f(B)=1 + (B-A)/(B-A)*(5-1) = 1 + 1*(5-1) = 5.

In general, the linear ecuation looks like:

f(x) = C + (x-A)*(D-C)/(B-A)
Easy peasy, isn't it?

Hope help!

Friday, October 24, 2014

NACE PHP Array - Statistical Classification of Economic Activities


The Statistical Classification of Economic Activities in the European Community commonly referred to as NACE, is a European industry standard classification system consisting of a 6 digit code.

Here I leave a PHP array with the categories of the first level. The European comunity give us a plain text file available hier.

A - Agriculture, forestry and fishing  
A1 - Crop and animal production, hunting and related service activities  
A1.1 - Growing of non-perennial crops  
A1.2 - Growing of perennial crops  
A1.3 - Plant propagation  
A1.4 - Animal production  
...


The PHP array version looks like:

public $NACE = array(
"A" => "Agriculture, forestry and fishing",
"A1" => "Crop and animal production, hunting and related service activities",
"A1.1" => "Growing of non-perennial crops",
"A1.2" => "Growing of perennial crops",
"A1.3" => "Plant propagation",
"A1.4" => "Animal production",
"A1.5" => "Mixed farming",
"A1.6" => "Support activities to agriculture and post-harvest crop activities",
"A1.7" => "Hunting, trapping and related service activities",
"A2" => "Forestry and logging",
"A3" => "Fishing and aquaculture",
"B" => "Mining and quarrying",
"B5" => "Mining of coal and lignite",
"B6" => "Extraction of crude petroleum and natural gas",
"B7" => "Mining of metal ores",
"B8" => "Other mining and quarrying",
"B9" => "Mining support service activities",
"C" => "Manufacturing",
"C10" => "Manufacture of food products",
"C11" => "Manufacture of beverages",
"C12" => "Manufacture of tobacco products",
"C13" => "Manufacture of textiles",
"C14" => "Manufacture of wearing apparel",
"C15" => "Manufacture of leather and related products",
"C16" => "Manufacture of wood and of products of wood and cork, except furniture; manufacture of articles of straw and plaiting materials",
"C17" => "Manufacture of paper and paper products",
"C18" => "Printing and reproduction of recorded media",
"C19" => "Manufacture of coke and refined petroleum products",
"C20" => "Manufacture of chemicals and chemical products",
"C21" => "Manufacture of basic pharmaceutical products and pharmaceutical preparations",
"C22" => "Manufacture of rubber and plastic products",
"C23" => "Manufacture of other non-metallic mineral products",
"C24" => "Manufacture of basic metals",
"C25" => "Manufacture of fabricated metal products, except machinery and equipment",
"C26" => "Manufacture of computer, electronic and optical products",
"C27" => "Manufacture of electrical equipment",
"C28" => "Manufacture of machinery and equipment n.e.c.",
"C29" => "Manufacture of motor vehicles, trailers and semi-trailers",
"C30" => "Manufacture of other transport equipment",
"C31" => "Manufacture of furniture",
"C32" => "Other manufacturing",
"C33" => "Repair and installation of machinery and equipment",
"D" => "Electricity, gas, steam and air conditioning supply",
"D35" => "Electricity, gas, steam and air conditioning supply",
"E" => "Water supply; sewerage; waste managment and remediation activities",
"E36" => "Water collection, treatment and supply",
"E37" => "Sewerage",
"E38" => "Waste collection, treatment and disposal activities; materials recovery",
"E39" => "Remediation activities and other waste management services",
"F" => "Construction",
"F41" => "Construction of buildings",
"F42" => "Civil engineering",
"F43" => "Specialised construction activities",
"G" => "Wholesale and retail trade; repair of motor vehicles and motorcycles",
"G45" => "Wholesale and retail trade and repair of motor vehicles and motorcycles",
"G46" => "Wholesale trade, except of motor vehicles and motorcycles",
"G47" => "Retail trade, except of motor vehicles and motorcycles",
"H" => "Transporting and storage",
"H49" => "Land transport and transport via pipelines",
"H50" => "Water transport",
"H51" => "Air transport",
"H52" => "Warehousing and support activities for transportation",
"H53" => "Postal and courier activities",
"I" => "Accommodation and food service activities",
"I55" => "Accommodation",
"I56" => "Food and beverage service activities",
"J" => "Information and communication",
"J58" => "Publishing activities",
"J59" => "Motion picture, video and television programme production, sound recording and music publishing activities",
"J60" => "Programming and broadcasting activities",
"J61" => "Telecommunications",
"J62" => "Computer programming, consultancy and related activities",
"J63" => "Information service activities",
"K" => "Financial and insurance activities",
"K64" => "Financial service activities, except insurance and pension funding",
"K65" => "Insurance, reinsurance and pension funding, except compulsory social security",
"K66" => "Activities auxiliary to financial services and insurance activities",
"L" => "Real estate activities",
"L68" => "Real estate activities",
"M" => "Professional, scientific and technical activities",
"M69" => "Legal and accounting activities",
"M70" => "Activities of head offices; management consultancy activities",
"M71" => "Architectural and engineering activities; technical testing and analysis",
"M72" => "Scientific research and development",
"M73" => "Advertising and market research",
"M74" => "Other professional, scientific and technical activities",
"M75" => "Veterinary activities",
"N" => "Administrative and support service activities",
"N77" => "Rental and leasing activities",
"N78" => "Employment activities",
"N79" => "Travel agency, tour operator and other reservation service and related activities",
"N80" => "Security and investigation activities",
"N81" => "Services to buildings and landscape activities",
"N82" => "Office administrative, office support and other business support activities",
"O" => "Public administration and defence; compulsory social security",
"O84" => "Public administration and defence; compulsory social security",
"P" => "Education",
"P85" => "Education",
"Q" => "Human health and social work activities",
"Q86" => "Human health activities",
"Q87" => "Residential care activities",
"Q88" => "Social work activities without accommodation",
"R" => "Arts, entertainment and recreation",
"R90" => "Creative, arts and entertainment activities",
"R91" => "Libraries, archives, museums and other cultural activities",
"R92" => "Gambling and betting activities",
"R93" => "Sports activities and amusement and recreation activities",
"S" => "Other services activities",
"S94" => "Activities of membership organisations",
"S95" => "Repair of computers and personal and household goods",
"S96" => "Other personal service activities",
"T" => "Activities of households as employers; undifferentiated goods and services producing activities of households for own use",
"T97" => "Activities of households as employers of domestic personnel",
"T98" => "Undifferentiated goods- and services-producing activities of private households for own use",
"U" => "Activities of extraterritorial organisations and bodies",

"U99" => "Activities of extraterritorial organisations and bodies");


Hope help!









Friday, July 11, 2014

MAMP. Access MySQL with PHP via CRON or Command line.


Again problems with MAMP.

I have a project in PHP which should access via CRON to MySQL running on MAMP.  With the default MAMP's configuration that is not possible. What to do?

OPTION A. Setting PATHs


1) Edit th .profile file (vi ~/.profile) and change the line

export PATH=/opt/local/bin:/opt/local/sbin:$PATH

to

export PATH=/Applications/MAMP/Library/bin/:/Applications/MAMP/bin/php5/bin/:/opt/local/bin:/opt/local/sbin:$PATH

2) Reload the .profile file

$ . ~/.profile

3) (Optional) If you have problems connecting to the database tray to create a symbolic link to /tmp/mysql.sock

sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock

Or more professional, add the next lines to your /etc/my.cnf file:

[mysqld]
socket=/Applications/MAMP/tmp/mysql/mysql.sock

[client]
socket=/Applications/MAMP/tmp/mysql/mysql.sock

Note: You can use also /etc/profile file if you want to do it for the rest of users.

OPTION B. Configuring a php.ini


1)  Check if your php exec has a defined config file

$ php --ini
Configuration File (php.ini) Path: /opt/local/etc/php5
Loaded Configuration File:         (none)
Scan for additional .ini files in: /opt/local/var/db/php5
Additional .ini files parsed:      /opt/local/var/db/php5/gd.ini,
/opt/local/var/db/php5/mbstring.ini,
/opt/local/var/db/php5/mcrypt.ini,
/opt/local/var/db/php5/mysql.ini,
/opt/local/var/db/php5/openssl.ini,
/opt/local/var/db/php5/zip.ini



2) Create/copy a default php.ini file in the config folder of your current PHP version. For example in my case: /opt/local/etc/php5/php.ini

Hope help!

Wednesday, May 14, 2014

Installing LAMP in CentOS (Linux Apache MySQL PHP)


Here you will find instructions on how to install Apache, MySQL and PHP on CentOS.

Installing Packages

1 Install the required packages with the following command: 

# yum install httpd php mysql mysql-server php-mysql

Downloading Packages:
(1/7): httpd-2.2.15-30.el6.centos.x86_64.rpm                            | 821 kB     00:00
(2/7): httpd-tools-2.2.15-30.el6.centos.x86_64.rpm                      |  73 kB     00:00
(3/7): mysql-5.1.73-3.el6_5.x86_64.rpm                                  | 894 kB     00:00
(4/7): mysql-server-5.1.73-3.el6_5.x86_64.rpm                           | 8.6 MB     00:00
(5/7): perl-DBD-MySQL-4.013-3.el6.x86_64.rpm                            | 134 kB     00:00
(6/7): php-5.3.3-27.el6_5.x86_64.rpm                                    | 1.1 MB     00:00
(7/7): php-mysql-5.3.3-27.el6_5.x86_64.rpm                              |  81 kB     00:00

2 Then, start the services by:

# /etc/init.d/httpd start
# /etc/init.d/mysqld start

Configuring Services 

Apache 2  

The configuration file of the Apache service is in the file /etc/httpd/conf/httpd.conf.  
The Apache documentation is available under http://httpd.apache.org/docs/.

MySQL  

You must create a root password before you can use the MySQL server in a production environment. The following code shows an example of how to do it:

# mysql
mysql> USE mysql;
mysql> UPDATE user SET Password=PASSWORD('newpassword') WHERE user='root';
mysql> FLUSH PRIVILEGES;
The configuration file for the MySQL service is available in /etc/my.cnf.
The documentation is available at http://dev.mysql.com/doc/

 

PHP  

You can find the configuration file for PHP in /etc/php.ini.
The documentation for PHP is available at http://www.php.net/docs.php

 

Launching services 

Run the following commands to ensure that the services are started at boot time:

# chkconfig httpd on
# chkconfig mysqld on

 Hope help
 

Friday, April 11, 2014

Patching OpenSSL for the Heartbleed Vulnerability CVE-2014-0160 in Mac OS X and Ubuntu / CentOS / Fedora

From 7th April we should update our OpennSSL version. Why? Security reasons. An OppenSSL vulnerability was disclosed which has been called one of the worst security holes in the last years. Let's do it!

OSX with MacPorts

To know your current version type: openssl version -a

myMac:~ Myself$ openssl version -a
OpenSSL 1.0.1f 6 Jan 2014

Opps, I have a bug in my system. It's time to update and upgrade the OpenSSL:
$ sudo port selfupdate
$ sudo port upgrade oppenssl
MyMac:~ Myself$ sudo port upgrade openssl 
--->  Computing dependencies for openssl
--->  Fetching archive for openssl
--->  Attempting to fetch openssl-1.0.1g_0.darwin_13.x86_64.tbz2 from http://nue.de.packages.macports.org/macports/packages/openssl
--->  Attempting to fetch openssl-1.0.1g_0.darwin_13.x86_64.tbz2.rmd160 from http://nue.de.packages.macports.org/macports/packages/openssl
--->  Installing openssl @1.0.1g_0
--->  Cleaning openssl
--->  Computing dependencies for openssl
--->  Deactivating openssl @1.0.1f_0
--->  Cleaning openssl
--->  Activating openssl @1.0.1g_0
--->  Cleaning openssl
--->  Updating database of binaries: 100.0%
--->  Scanning binaries for linking errors: 100.0%

--->  No broken files found.

Now we can check again our version to be sure that we have an updated openssl version:

MyMac:~ Myself$ openssl version -a
OpenSSL 1.0.1g 7 Apr 2014

Ubuntu:

$ sudo apt-get update
$ sudo apt-get upgrade
$ openssl version -a

CentOS/Fedora

$ sudo yum -y install openssl
$ openssl version -a

Hope help!

Thursday, April 10, 2014

How to get the internal IP address of our machine using Java (for Raspberry Pi)


Hello, today... more Java

First of all, eth0 is your ethernet card. They are labelled "ethX" starting with an X of 0, so if you had two ethernet cards, the second would be "eth1".

Now, the idea is to get the IP address of my machine (small Raspberry Pi) using Java.  Normally, we can try simply with InetAddress.getLocalHost(). But if we have more than one ethernet card or a loop perhaps this method doesn't work.

A possible solution could be:
InetAddress internalIP;

Enumeration nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)) {
    if(netint.getName().equals("eth0")) {
        Enumeration inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            internalIP = inetAddress;
            break;
        }
    }
}

Now we can use internalIP.getHostAddress() to show the IP address like a string.

Hope help!!

Friday, March 21, 2014

Installing Laravel 4 in Ubuntu Server with PHP 5.5


Today we are going to learn how to install Laravel 4 with PHP 5.5 on Ubuntu Server from cero.

1) Adding a repository

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:ondrej/php5

2) Updating repositories

sudo apt-get update
sudo apt-get upgrade

3) Installing PHP 5.5

sudo apt-get install php5 php5-mcrypt
php -v

PHP 5.5.9-1+sury.org~precise+1 (cli) (built: Feb 13 2014 15:53:53)
(Optional)
sudo apt-get install php5-gd php5-curl php5-cli php5-cgi php5-dev
4) Enable Apache mod_rewrite to use Laravel pretty URL's

sudo e2enmod rewrite
sudo apache2 restart

5) Installing Composer

curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

6) Installing Laravel in your desired folder (Ex. /var/www/projectname)

composer create-project laravel/laravel projectname

7) Setting up the permisions

chmod -R 775 /var/www/projectname/app/storage

8) Setting up Apache. Edit /etc/apache2/sites-available/default for example and set your configuration. 
sudo service apache2 reload

Hope help!




Thursday, March 13, 2014

How to run an script/command when a USB is connected to the port with udev in a Raspberry Pi

How to run an script/command when a USB is connected to the port.

Well, first we have to discover some information about the USB device and then we will be able to define rules to indicate the system which script we want to run.

Connect the USB device and enter the next commands

1) Get the serial number of the device

$ udevadm info -a -n /dev/ttyUSB0 | grep '{serial}' | head -n1

    ATTRS{serial}=="1234567890"
    

2) Get the Id Vendor

$ udevadm info -a -n /dev/ttyUSB0 | grep idVendor | head -n1

    ATTRS{idVendor}=="0403"


3) Get the Product Id

$ udevadm info -a -n /dev/ttyUSB0 | grep idProduct | head -n1
 
    ATTRS{idProduct}=="6001"


Now with this information we can write the UDEV rule:

4) Create a new file /etc/udev/rules.d/99-usbserial.rules and insert the line (one line):

$ sudo vi /etc/udev/rules.d/99-usbserial.rules

ACTION=="add", SUBSYSTEM=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", RUN+="YOURSCRIPT_FULLPATH"


5) Save the file and reset the udev service

$ sudo /etc/init.d/udev restart

Ready, now when the USB device is connected the script YOURSCRIPT_FULLPATH will be launch. You also can see the log details of udev in /var/log/daemon.log.

(Note: In my rule I didn't use the serial number :))

Hope help!

Wednesday, March 12, 2014

HTTP POST request with JSON String in JAVA for Raspberry Pi - libhttpclient-java

Hi there,
Continuing with the last project I want to send the data collected by the Raspberry Pi to my API service. I need to do that using JAVA, so I decided to use libcommons-httpclient-java , a Java library for creating HTTP clients.

Let's install it:

pi@raspberrypi ~ $ sudo apt-get install libhttpclient-java
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
  libhttpcore-java
The following NEW packages will be installed:
  libhttpclient-java libhttpcore-java
0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.
Need to get 671 kB of archives.
After this operation, 892 kB of additional disk space will be used.
Do you want to continue [Y/n]? 

...


We can compile using this library (javac -cp ...) or include the new library in ore CLASSPATH variable:

$ export CLASSPATH=$CLASSPATH:/usr/share/java/httpclient.jar
$ export CLASSPATH=$CLASSPATH:/usr/share/java/httpcore.jar
$ export CLASSPATH=$CLASSPATH:/usr/share/java/commons-logging-1.1.1.jar


Now, it's time to code the java http client which post the data to the server (not explained in this post).

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

import java.util.List;
import java.util.ArrayList;

public class ApacheHttpClientPost {
    public static final int HTTP_OK = 200;
    private String restUrl="http://192.168.188.20/arest/serverside.php";
   
    public void setRestUrl(String url) {
        this.restUrl = url;
    }
   
   
    public int sendJson(String jsonString) {

        int responseStatusCode = -1;
       
        try {

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(this.restUrl);

            List nameValuePairs = new ArrayList(1);
            nameValuePairs.add(new BasicNameValuePair("tel", jsonString));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpClient.execute(post);


            responseStatusCode = response.getStatusLine().getStatusCode();
            System.out.println(responseStatusCode);
            if (responseStatusCode > 200 && responseStatusCode < 300) {
                throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
            }
   
            BufferedReader br = new BufferedReader(
                new InputStreamReader((response.getEntity().getContent())));
   
            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
   
            httpClient.getConnectionManager().shutdown();
           
        } catch (MalformedURLException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return responseStatusCode;
    }
   
    public static void main(String[] args) {
        ApacheHttpClientPost me = new ApacheHttpClientPost();
       
        me.sendJson("{data: \"data content\"}");
    }
}


Don't forget to set up a server and change the "restUrl" URL. To compile and execute the code run the next commands:

pi@raspberrypi ~/java $ javac ApacheHttpClientPost.java
pi@raspberrypi ~/java $ java ApacheHttpClientPost

200
Output from Server ....

Array
(
    [tel] => {data: "data content"}
)


Of course, the code works but it is an extract from the project. I recomment you to use it as a reference.

Hope help!





Tuesday, March 11, 2014

Encoding JSON in Java with libjson-simple


Before start to encoding/decoding JSON using Java, we will need to install a JSON library. In this example I will use libjson-simple as follow:

pi@raspberrypi ~/$ sudo apt-get install libjson-simple-java

Once we have installed the library we need to update our CLASSPATH system variable:


pi@raspberrypi ~/$ export CLASSPATH=$CLASSPATH:/usr/share/java/json_simple-1.1.jar
Now we are ready to coding. Let use the next code:

import org.json.simple.JSONObject;

class JsonEncodeDemo
{
   public static void main(String[] args)
   {
      JSONObject obj = new JSONObject();

      obj.put("protocol", "mbus");
      obj.put("length", new Integer(168));
      obj.put("manufacturer", new Integer(4897));
      obj.put("valid", new Boolean(true));

      System.out.print(obj);
   }
}

To execute the code we can use:

pi@raspberrypi ~/java $ javac JsonEncodeDemo.java
pi@raspberrypi ~/$ java JsonEncodeDemo{"valid":true,"protocol":"mbus","manufacturer":4897,"length":168}

Hope help!!

Raspberry Pi. Read data from USB Serial Port using Java and Python.


Hello,

Recently I bought my first Raspberry Pi, and as a first project I decided to implement a wireless package filter.. Here I'm going to show how to read the USB (serial port) using Linux on a Raspberri Pi.

Using Python

First, you have to install the basic packages to read serial port

pi@raspberrypi ~ $ sudo apt-get install python-serial

In my case I am using FTDI wireless USB device, connected to the port /dev/ttyUSB0. You can check the state of your USB stick and the kernel modules associted to it using the command:

pi@raspberrypi ~ $ dmesg
...
[    5.822444] usbcore: registered new interface driver usbserial
[    5.988161] usbcore: registered new interface driver usbserial_generic
[    6.169752] usbserial: USB Serial support registered for generic
[    6.594175] usbcore: registered new interface driver ftdi_sio
[    6.683308] bcm2708-i2s bcm2708-i2s.0: Failed to create debugfs directory
[    6.870064] usbserial: USB Serial support registered for FTDI USB Serial Device
[    7.198032] ftdi_sio 1-1.2:1.0: FTDI USB Serial Device converter detected
[    7.336725] usb 1-1.2: Detected FT232RL
[    7.533758] usb 1-1.2: Number of endpoints 2
[    7.639343] usb 1-1.2: Endpoint 1 MaxPacketSize 64
[    7.729645] usb 1-1.2: Endpoint 2 MaxPacketSize 64
[    7.808760] usb 1-1.2: Setting MaxPacketSize 64
[    7.879211] usb 1-1.2: FTDI USB Serial Device converter now attached to ttyUSB0
...


The loaded modules for my devices are shown with the command:

pi@raspberrypi ~ $ lsmod
Module                  Size       Used by

...
ftdi_sio               29846       0
usbserial              26929       1 ftdi_sio
...


You can get more information about your USB devices as follow:

pi@raspberrypi ~ $ lsusb
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.
Bus 001 Device 004: ID 0403:6001 Future Technology Devices International, Ltd FT232 USB-Serial 


Once we know that the device is connected and has beed detected we can start coding. In my case the parameters to fetch the device are: 9600 8N1.

import serial
import sys

# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
)
 
# Print the bytes feched 
while True:
    n = ser.inWaiting()

    if n>0:

            ch=ser.read(size=1)
            print("%02x" % ord(ch),  end='')

This is a very basic code that read data from /dev/ttyUSB0 and print it hexadecimal pair format.

Now you can include your code to detect different telegrams or patterns, por example using:

            if '0x68' == hex(ord(ch)):
                    data="blablabla"

Using Java

If we want to do the same using Java, we need to install first the RXTX library (and of course Java SDK)

pi@raspberrypi ~ $ sudo apt-get install librxtx-java
Then you need to update your local varibles: CLASSPATH and LD_LIBRARY_PATH, for example as follow:

pi@raspberrypi ~ $ export CLASSPATH=$CLASSPATH:/usr/share/java/RXTXcomm.jar
pi@raspberrypi ~ $ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/jni


Now you are ready to code. A basic example is here presented:

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;

public class TestSerialComm {
    private CommPortIdentifier portIdentifier;
    private SerialPort serialPort;
    private InputStream in;

    public static final boolean DEV_MODE = true;
   
    void connect( String portName ) throws Exception {
        this.portIdentifier = CommPortIdentifier.getPortIdentifier( portName );

        if( portIdentifier.isCurrentlyOwned() ) {
       
          System.out.println( "Error: Port is currently in use" );
         
        } else {
       
            if(DEV_MODE) System.out.println("Starting...");
           
            int timeout = 2000;
            CommPort commPort = portIdentifier.open( this.getClass().getName(), timeout );

            if( commPort instanceof SerialPort ) {
                this.serialPort = ( SerialPort )commPort;
                serialPort.setSerialPortParams( 9600 ,
                                            SerialPort.DATABITS_8,
                                            SerialPort.STOPBITS_1,
                                            SerialPort.FLOWCONTROL_NONE );

                this.in = serialPort.getInputStream();

            } else {
                System.out.println( "Error: Only serial ports are handled by this example." );
            }
        }
    }

    public void fetchTelegrams() throws Exception {
        int b = -1;

        if(DEV_MODE) System.out.println("Inside loop...");

        while (true) {

            // Read new byte
            b = this.in.read();        


            // Negative value means no-data
            while(b<0 br="" nbsp="">                             b = this.in.read();


            // We have data
            System.out.print(this.hexify(b));             

             // Your code is here
             // ....
        }

    }
   
    /*
     * Convert received byte (int form) to HEX couples.
     */
    public String hexify(int input){
        String output = Integer.toHexString(input).toUpperCase();
        if(output.length() == 1)
            output = "0"+output;
        return output;
    }

    public static void main( String[] args ) {
        try {
            TestSerialComm test = new TestSerialComm();
            test.connect( "/dev/ttyUSB0" );
                                       
            // Infinity loop
            test.fetchTelegrams();
            System.exit(0);
               
        } catch( Exception e ) {
          e.printStackTrace();
        }
    }
}


To compile this example, you can for example do this:

pi@raspberrypi ~/java $ javac TestSerialComm.java
pi@raspberrypi ~/java $ java TestSerialComm
Starting...
Running...

74495041919473055087219194730...

I hope help!!