poniedziałek, 30 listopada 2015

Glassfish - instalacja na Linux Mint (domyślna konfiguracja)

Instalacja jest banalnie prosta: ściągamy plik zip z oficjalnej strony i rozpakowujemy (po wcześniejszym upewnieniu się, że mamy zainstalowaną javę). Kolejnym krokiem tylko dla wygody jest dodanie ścieżki do glassfisha do zmiennej PATH. Aby na trwałe zmodyfikować tą zmienną środowiskową należy edytować plik /home/nazwa_profilu/.profile (dotyczy wersji Linux Mint) i dopisać na końcu:
export PATH=$PATH:/opt/glassfish4/bin
Następnie uruchamiamy Glassfish'a wywołując komendę:
asadmin start-domain
(bazuje, że w zmiennej $PATH jest podana ścieźka do glassfisha, jeśli tego nie zrobiliśmy to należy wywołać SciezkaDoGlassfish/bin/asadmin start-domain) po wywołaniu powyższej komendy na konsoli zostanie wyświetlone podsumowanie. Jeśli nie ma informacji o błędzie to możemy wpisać w przeglądarkę adres: http://moje-ip:8080/ (domyślny port na którym startuje glassfish to 8080). Powinna pokazać nam się strona jak na zdjęciu poniżej:
Następnie możemy odblokować dostęp do webowego panelu administracyjnego. Znajduje się on pod adresem http://moje-ip:4848. Aby to zrobić wpisujemy w konsoli:
asadmin change-admin-password
#zmieniamy hasło# 
asadmin enable-secure-admin
asadmin restart-domain
W tym momencie można już deploy'ować aplikacje. Dla wygody należy zapewnić aby Glassfish był zawsze uruchamiany po starcie systemu. Aby tak było dopisujemy do pliku /etc/rc.local komendę (są inne, lepsze rozwiązania ale o tym w innym poście):
asadmin start-domain

VPN na Raspberry Pi

Stawiając OpenVPN bazowałem na artykule ze strony: http://www.linuxuser.co.uk/tutorials/vpn-tutorial-access-your-network-anywhere (https://web.archive.org/web/20150215041331/http://www.linuxuser.co.uk/tutorials/vpn-tutorial-access-your-network-anywhere).

Step by step
Step 01 Install OpenVPN on the server
Install OpenVPN using the package manager. For Red Hat, type yum install openvpn or apt-get install openvpn on Debian (both root). In addition, install easy-rsa, a collection of scripts that aid in the creation of the certificates and keys that we need.

Step 02 Copy easy-rsa scripts
We can’t run easy-rsa from where it is installed because we need to alter it. Find the installation directory with find /usr -name easy-rsa. Copy the directory to your current directory with (for example) cp -r /usr/share/ easy-rsa/. and move into it with the cd command.

Step 03 Install OpenVPN on the server
Open the file vars in a text editor. The official OpenVPN documentation recommends that you edit at least the KEY_COUNTRY, KEY_PROVINCE, KEY_CITY, KEY_ORG and KEY_EMAIL fields. Set KEY_CN to ‘server’. Close and save the file.

Step 04 Build server certificates and keys
Type source ./vars followed by ./clean-all and then ./build-ca. Fill in the questions when prompted – you should be able to hit Return to accept the defaults in most cases. Build the certificates and keys for the server with the command ./build-key-server server. Answer questions as before and accept server as the Common Name. Don’t specify the challenge password or optional company name when asked. Answer y when asked about signing the certificate and when asked to commit. Diffie-Hellman parameters are an element in the encryption scheme that OpenVPN employs. Type ./build-dh to create the parameter file.

Step 05 Copy the server keys
Enter the keys directory with the cd command, and type ls keys to examine the key files that we have created. Use cp * /etc/openvpn/ (as root) to copy all of the keys to where OpenVPN can see them. Then do chmod 400 /etc/openvpn/{server.key,server. crt,ca.crt,ta.key}.

Step 06 Generate three client keys
Use the command ./build-key client1 to generate the first of the client keys. When prompted, accept client1 as the common name. Each key must have a unique common name. Now repeat the procedure for two more client keys. As before, agree to sign the certificate and commit.

Step 07 Begin server configuration
The server and each client use a configuration file located in the /etc/openvpn folder. On the server, when the OpenVPN service starts, it scans that directory and launches a service instance for every valid configuration file it finds. Start by shutting down the OpenVPN service by typing service openvpn stop (as root).

Step 08 Locate the example configuration
Use find /usr -name server.conf* to locate the example server configuration file. Use cut and paste within the terminal to copy it to the current directory with the cp [name of file] . command sequence. If it has a .gz extension, it’s compressed. If so, decompress with gunzip [name of file].

Step 09 Edit server configuration
Open server.conf in a text editor and give it a quick examination to get an idea of what you can change, but we’ll leave most of it as it is. For now, just add /etc/openvpn/ to the start of the key filenames.

Step 10 Start the server
For now, we’ll start the server manually so that we can see the text output and check for errors. Type openvpn server.conf (as root). If everything is working okay, the final message should be ‘Initialization Sequence Completed’.

Step 11 Configure the client
Move to another Linux machine on your LAN (the client). Install OpenVPN using the package management system. Now run find /usr -name client.conf to find the example client configuration file and copy it to the current directory. Copy the files client1.key, ca.crt and client1.crt to /etc/openvn/ on the client machine. How you do this is up to you, but bear security in mind as anyone who has these files can, potentially, use them to access your server. A memory stick (delete them afterwards) or a trusted network such as your LAN should be fine.

Step 12 Edit the client configuration
Open client.conf in a text editor. Change remote to the IP address of the server. For now, use the IP address of the server on your LAN (run ifconfig on it). Later, we’ll change this to the external IP address so that it can be accessed from the internet. Change the CA certificate (ca) to ca.crt, the user certificate (cert) to client1.crt and the private key (key) to client1.key, each with /etc/openvpn/ at the beginning of the name. Each client needs a copy of the CA and unique versions of the other two files.

Step 13 Test the client
Type openvpn client.conf (as root) to start the client. Type ifconfig to confirm the creation of the tun0 device. If you can ping the server from the client by typing ping 10.8.0.1, you have now established a tunnelled, encrypted connection between the client and the server.

Step 14 Enable packet forwarding
As it stands, we can connect to the server, via the tunnel, but we can’t yet access the internet. Start by editing /etc/sysctl.con and uncomment the line net/ipv4/ip_forward=1 to enable packet forwarding. Now restart the server machine.

Step 15 Forward traffic with iptables
On the server, type iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE (as root) to enable forwarding of traffic through the tunnel to the internet- connected interface (eth0). Install the dnsmasq package to your system. Add the line interface=tun0 to /etc/dnsmasq.conf. Restart dnsmasq by typing service dnsmasq restart.

Step 16 Set up routing for the client
Add the lines push “redirect-gateway def1″ and push “dhcp-option DNS 10.8.0.1″ to server.conf. This causes the clients to execute the appropriate route commands to direct all network traffic via the VPN. You may have to manually add the DNS server to the client: add the line nameserver 10.8.0.1 to /etc/resolvconf/ resolv.conf.d/head and type resolvconf -u (all as root). You should now be able to ping and browse to sites on the internet from the client.

Step 17 Forward traffic with iptables
On the server, copy server.conf to /etc/ openvpn/. We now control the OpenVPN server with service openvpn [command]. ‘Command’ can be start, stop or restart and the check command makes the service start on boot. Add the iptables we used to the end of /etc/rc.local.

Step 18 Connecting from the outside
Set up your router to forward UDP port 1194 to the IP address of your server. How you do this depends on the model of your router (see portforward.com for a comprehensive database of router models). Update the remote field in your client.conf files to point to the external IP address of your network (use www.whatismyip.com to find it). Consider using a dynamic IP service such as No-IP (www.noip.com) so that you don’t have to update the clients every time the address on your router changes.

Step 19 Connecting from an Android device
Most Android phones and tablets don’t include built-in OpenVPN support. Search for an OpenVPN client on Google Play. Your choice of client may depend on compatibility with your device, and some applications require a rooted device. Copy the key files to your SD card and use the setup page of the client.
Step 20 Connecting from a Windows client
The OpenVPN website (openvpn.net) has a client that runs on Windows. Copy the three client files to the machine, then install the client and follow the on-screen prompts. The Windows client can make use of the push directives that we added to server.conf, so we don’t need to set up DNS manually.



Początkowe kroki są jasne i nie wymagają opisu.

Problem może być od kroku 14 "Step 14 Enable packet forwarding". W artykule jest literówka i chodzi o edycję pliku "/etc/sysctl.conf".

Krok 15 "Step 15 Forward traffic with iptables" - wykonałem tylko komendę:
iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE

ponieważ nie interesowało mnie stawianie dns.
Powyższa komenda działa tylko do restartu! Należy dopisać ją do pliku /etc/rc.local
Dzięki tej koemndzie możemy się dostać nie tylko na serwer gdzie jest vpn a na każdy komputer w LANie

Krok 16

Oprócz powyższych edytujemy plik: /etc/openvpn/server.conf i dopisujemy push "route 192.168.1.0 255.255.255.0":

# Push routes to the client to allow it
# to reach other private subnets behind
# the server.  Remember that these
# private subnets will also need
# to know to route the OpenVPN client
# address pool (10.8.0.0/255.255.255.0)
# back to the OpenVPN server.
push "route 192.168.1.0 255.255.255.0"



I to wystarczy aby działał nam VPN. Oczywiście potrzebne jest stałe IP lub w przypadku jego braku trzeba skorzystać z serwisu noIP.me.

poniedziałek, 5 października 2015

Programowanie Arduino Pro Mini za pomocą USBasp

W celu zaprogramowania arduino mini ja korzystam z programatora USBasp. Poniżej schemacik programowania mikrokontrolera. Istotny dla nas jest opis wyjść z programatora.

Cały artykuł dostępny na majsterkowo.pl.

A tutaj opis które piny i jak z arduino mini trzeba podłączyć do programatora.
Cały artykuł dostępny na instructables.

Po poprawnym podłączeniu uruchamiamy np Arduino IDE. Zmieniamy typ płytki na Arduino Pro or Pro Mini 5v / Atmega 328. Nastepnie ustawiamy jaki posiadamy programator. W moim przypadku: Tools -> Programmer -> UsbAsp. Na koniec zostało wrzucenie sketchu na arduino. Aby to zrobić wybieramy opcję: File -> Upload using programmer.

A tutaj link do artykułu gdzie pokazane jest jak programować arduino mini za pomocą większego brata Arduino Uno.

Oświetlenie LED w kuchni

Ostatnio postanowiłem zrobić dla ukochanej żony oświetlenie pod szafkowe, aby nie musiała zmywać w ciemnościach ;).
Do zrobienia projektu wykorzystałem następujące części:
* Taśma LED 12V biała ciepła
* Zasilacz wodoodporny IP67 (ja miałem 50W)
* Arduino Pro Mini
* Tip31C
* Czujnik odległości HC-SR04
* Wtyk DC Power Jack męski i damski

Poniżej mini-schemat:


Wszystko zamknąłem w obudowę:


Pomocne przy lutowaniu wtyków do zasilania okazały się poniższe zdjęcia:
Tu warto zwrócić uwagę, że należy oba piny GND podłączyć do masy.
I drugie zdjęcie:



Program został napisany z wykorzystaniem Arduino IDE. Jak załadować projekt na arduino mini opiszę w osobnym poście. Poniżej kod programu. Ma on za zadanie włączać oświetlenie gdy zbliżymy rękę do czujnika na max 20cm. Odczyt sygnału ustawiłem na 1,2sekundy. Kolejne zbliżenie ręki ma wyłączyć taśmę LED.
Wszystkie odwołania do Serial można wyrzucić - były tylko pomocne na etapie projektowania i debugowania.
/*
HC-SR04 Ping distance sensor]
VCC to arduino 5v; GND to arduino GND
Echo to Arduino pin 7; Trig to Arduino pin 8
*/

#define echoPin 7
#define trigPin 8
#define dioda 9
int isEnable = 0;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(dioda, OUTPUT);
}

void loop() {
  // send a pulse on the trigger pin to initiate measurement
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // the length of the pulse on the echo pin is proportional to the distance
  long duration = pulseIn(echoPin, HIGH);
  long distance = (duration/2) / 29.1;

  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
    digitalWrite(dioda, HIGH);
      delay(1200);
      digitalWrite(dioda, LOW);
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
    if(distance < 20) {
      if(isEnable == 0) {
        isEnable = 1;
        digitalWrite(dioda, HIGH);
      }
      else if(isEnable == 1) {
        isEnable = 0;
        digitalWrite(dioda, LOW);
      } 
    }
  }
  delay(1200);
 
}

Całość prezentuje się jak na filmiku poniżej. Zostało podłączenie docelowego zasilacza oraz zamaskowanie kabli.


piątek, 21 sierpnia 2015

Zdalne debugowanie skryptu Python z Eclipse na Raspberry Pi

Ostatnio chciałem zdalnie przedebugować aplikację na OSMC. Na poniższej stronie jest wiele potrzebnych informacji, ale jednak niestety nie wszystkie. 
http://kodi.wiki/view/HOW-TO:Debug_Python_Scripts_with_Eclipse

Jasno i gładko jest do punktu 3.4.4 tj Copy pysrc in XBMC Python install. Nie jest dokładnie opisane co należało zrobić w przypadku Linuxa. Po chwili kombinowania ściągnąłem na OSMC repozytorium SuperRepo a następnie zainstalowałem PyDev. W moim przypadku zainstalował się on w
/home/osmc/.kodi/addons/script.module.pydevd.

Następnie na malince wykonałem polecenie:
python -c "from distutils.sysconfig import *; print(get_python_lib())"

 które zwróciło mi ściezkę, do której musiałem wgrać pliki z pydev.
Wykonałem polecenia:
cd /usr/lib/python2.7/dist-packages
mkdir pysrc
cp -rvp /home/osmc/.kodi/addons/script.module.pydevd/* /usr/lib/python2.7/dist-packages/pysrc/

Po skopiowaniu plików, w folderze pysrc musiałem utworzyć pusty plik __init__.py - bez tego zdalne debugowanie mi nie działało. Na sam koniec do źródeł programu co chciałem przedebugować dodałem
# Make pydev debugger works for auto reload.
    # Note pydevd module need to be copied in XBMC\system\python\Lib\pysrc
    try:
        import pysrc.pydevd as pydevd # with the addon script.module.pydevd, only use `import pydevd`
 # stdoutToServer and stderrToServer redirect stdout and stderr to eclipse console
        pydevd.settrace('ipSkadChcemyDebugow', stdoutToServer=True, stderrToServer=True)
    except ImportError:
        sys.stderr.write("Error: " +
            "You must add org.python.pydev.debug.pysrc to your PYTHONPATH.")
        sys.exit(1)

wgrałem na malinkę, uruchomiłem program i voila!

niedziela, 31 maja 2015

Sprawdzenie predkości zapisu/odczytu na dysku

Na raspberry pi 2 w celu sprawdzenia prędkości odczytu z karty należy zainstalować hdparm i wywołać:
# hdparm -t --direct /dev/sda
W celu sprawdzenia prędkości zapisu:
$ sync;time bash -c "(dd if=/dev/zero of=bf bs=8k count=500000; sync)"

sobota, 18 kwietnia 2015

Raspberry Pi Samba - udostępnianie zasobu, prosty serwer NAS

Ostatnio zapragnąłem mieć dostęp do przenośnego dysku z multimediami z każdego miejsca bez zabierania tegoż dysku. Wiele osób odradza wykorzystywanie Raspberry Pi jako serwer NAS. Polecają po prostu podłączenie dysku przez usb do rutera lub kupno dedykowanego serwera. W sumie stwierdziłem, że czemu by nie podłączyć dysku do rutera skoro posiada złączę usb. Zdecydowałem się na to rozwiązanie mimo, że spotkałem się z opiniami, że takie rozwiązanie nie zawsze działa. No i niestety takie rozwiązanie z niewiadomych mi względów powodowało przejściowe problemy z internetem - po prostu co jakiś czas modem rozłączał dostęp. Nie chciało mi się szukać przyczyny czy to firmware rutera czy jakieś problemy z zasilaniem. Po prostu stwierdziłem, że lepiej i szybciej będzie podpiąć dysk pod malinkę i udostępnić zasoby przez Sambe. Dysk który posiadam ma pojemność 2TB ale jest na usb 2. Predkość zapisu i odczytu nie będzie imponująca, ale spokojnie wystarczy do domowego użytku (w sumie do tej pory też wystarczała). Zwłaszcza, że Raspbery Pi nie posiada złącza SATA lub USB3. Jeśli komuś zależy na serwerze NAS z większą wydajnością polecam zapoznanie się z Banana Pi (posiada interfejs SATA). Zaczynamy od podłączenia dysku przez usb do maliny. Sprawdzamy czy Raspbian go widzi i jaka ma nazwę:
sudo fdisk -l
w moim przypadku widać, ze dysk 2TB jest pod /dev/sda1.

U mnie dysk był od razu zamontowany więc użyłem do jego odmontowania następującego polecenia:
umount /dev/sda1
Ponieważ mój dysk zewnętrzy ma system plików NTFS to zainstalowałem:
sudo apt-get install ntfs-3g
W internecie znalazłem informację, że: ntfs-3g for NTFS drives vfat for FAT32 drives ext4 for ext4 drives kolejny krok to założenie folderu gdzie chce zamontować dysk zewnętrzny:
sudo mkdir /media/USBZEWN
i zamontowanie dysku w ustalonym przeze mnie folderze:
sudo mount -t auto /dev/sda1 /media/USBZEWN
Niestety po restarcie raspberry musielibysmy montować dysk od nowa. Aby robiło się to automatycznie należy wyedytować plik /etc/fstab i dopisać na koncu:
/dev/sda1 /media/USBZEWN auto defaults 0 2

Teraz musimy pobrac repozytorium samby:
sudo apt-get install samba samba-common-bin
Robimy kopie i przechodzimy do edycji pliku konfiguracyjnego samby:
sudo cp /etc/samba/smb.conf /etc/samba/backup_smb.conf
sudo nano /etc/samba/smb.conf
W moim przypadku w Share definitions dodałem dwa udziały:
[MEDIA_public]
   commment = Server NAS Public
   path = /media/USBZEWN
   guest ok = yes
   read only = yes

[MEDIA_2TB]
   comment = Dysk zewnetrzny DLNA 2TB
   path = /media/USBZEWN
   create mask = 0777
   directory mask = 0777
   valid users = @users
   force group = users
   public = yes
   browseable = yes
   read only = no
Pierwszy jest tylko readonly czyli tylko do odczytu, ale nie wymaga za to uwierzytelniania. Do drugiego mogą zapisywać, ale tylko wybrani uzytkownicy. Jak ich dodać? Zacznijmy od założenia użytkownika do Raspbiana:
sudo useradd radek
sudo passwd radek
Jesli w konfiguracji Samby ustawiliśmy force group = users to naszego nowego użytkownika musimy dodać do tej grupy "users". Jeśli tego nie zrobimy to windows nie da nam dostępu do udziału:
sudo gpasswd -a radek users
groups radek
Nastepnie musimy dodac użytkownika do samby:
sudo smbpasswd -a radek
UWAGA: logowanie do udzialu bedzie tym hasłem który ustalimy w powyższym kroku. Nie logujemy się na hasło do użytkownika z Raspbiana. Na koniec resetujemy sambe:
sudo service samba restart
Teraz będąc poza domową siecią moge np na laptopie uruchomić OpenVPNa , nastepnie w windowsie wpisać sciezkę \\IP_LOKALNE_RASPBERRY i bedę miał widoczne udziały z Samby.

poniedziałek, 2 lutego 2015

Sprawdzenie rozmiaru folderów pod linuxem

Wystarczy wywołać komendę:
find /SCIEZKA -maxdepth 1 -type d -exec du -hs {} \; | sort -nr

a jeśli chcemy posortować po rozmiarze w bajtach:
find /mnt/kardio/ -maxdepth 1 -type d -exec du -s {} \; | sort -nr

piątek, 2 stycznia 2015

Wywołanie C z Javy - JNI na przykładzie czujnika temperatury DHT11

W poprzednim wpisie na blogu pokazałem jak przygotować bibliotekę SO i wywołać metody w javie wykorzystując Java Native Interface. Poniżej przedstawiam bardziej rozbudowany przykład gdzie klasa C odwołuje się dodatkowo do biblioteki wiringPi. Dzięki temu będę mógł z poziomu Javy wywołać metodę w C odczytującą temperaturę z czujnika DHT11.

Pierwsze kroki jakie należy wykonać są dokładnie opisane w poprzednim artykule. Różnica jest przy kompilowaniu i tworzeniu pliku SO (shared object - objekt współdzielony, odpowiednik windowsowego pliku DLL).

W celu kompilacji wywołujemy kod:
gcc -fPIC -c DHT11.c -I $JAVA_HOME/include -I /usr/local/include/


Należy upewnić się, że mamy ustawioną zmienną środowiskową JAVA_HOME.
Aby to sprawdzić należy wywołać:
echo $JAVA_HOME

Jeśli zostanie zwrócony pusty wynik to trzeba ustawić tą zmienną przez polecenie:
export JAVA_HOME="scieżkaDoJavy"


Po wywołaniu powyższej komendy kompilacji zostanie utworzony plik DHT11.so. Następnie wywołujemy:
gcc DHT11.o -shared -o libDHT11.so -Wl,-soname,DHT11 -L/usr/local/lib -lwiringPi

gdzie:
-o - nazwa pliku wynikowego, musi być z przedrostkiem "lib", nazwa musi się zgadzać z nazwą w klauzuli System.loadlibrary() w Javie
-L/usr/local/lib - ścieżka gdzie szukać skompilowanego kodu źródłowego biblioteki (plików obiektowych)
-lwiringPi - linkujemy do kompilatora bibliotekę wiringPi - wcześniej należy ją zainstalować zgodnie z instrukcjami ze strony http://wiringpi.com/download-and-install/

Jeśli nie dodamy -L/sciezka -lwiringPi to będziemy mieli do czynienia z błędem:
java: symbol lookup error: ..../libDHT11.so: undefined symbol: pinMode


Zostało sprawdzenie czy wszystko działa:
java -Djava.library.path=. DHT11


I na ekranie konsoli uzyskamy odczyt temperatury z czujnika DHT11