Creato da l30n1d4 il 12/11/2013

Raspberry Pi Tank

Appunti di codice per l'utilizzo del Raspberry Pi

 

Storj Share con Raspberry Pi

Post n°17 pubblicato il 14 Dicembre 2017 da l30n1d4
 

sudo apt-get update && sudo apt-get dist-upgrade

sudo apt-get install git python build-essential -y

sudo fdisk /dev/hda

- cancellare tutte le partizioni (comando d) e creare una nuova (comando n). Alla fine scrivere col comando w

sudo mkfs -t ext4 /dev/hda1

- creare filesystem ext4

mkdir /mnt/storj

- creare cartella

sudo nano /etc/fstab

- modificare file fstab

/dev/sda1 /mnt/storj ext4 rw,defaults 0 2

e2label /dev/sda1 storj

- inserire etichetta partizione

mount -l

- verificare partizioni

sudo chmod a+rwx /mnt/storj

- dare permessi a tutti

 

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.3/install.sh | bash

- installare script e successivamente uscire e rientrare nella shell di ssh

nvm install --lts

npm install --global storjshare-daemon

storjshare create --storj=YOUR_STORJ_TOKEN_WALLET_ADRESS --storage=/mnt/storj/

sudo nano start-farming.sh

storjshare daemon

storjshare start --config /path/to/storjconfig/xxxx.json

- salvare il file

sudo chmod +x ~/start-farming.sh

- dare i permessi di esecuzione dello script

crontab -e

@reboot /home/pi/start-farming.sh

- salvare al riavvio l'esecuzione dello script

- riavviare

 

- comandi utili: storjshare status

 

 
 
 

Telegram Bot with Raspberry Pi

Post n°16 pubblicato il 28 Luglio 2017 da l30n1d4
 

sudo apt-get install python-pip
sudo pip install telepot

sudo nano bot.py
_________________________________________________________
import commands
import subprocess
from datetime import timedelta
import sys
import os
import telepot
import datetime
import time
#--------import per la request di json
import requests
#--------import per il parser dei caratteri speciali
try:
    from HTMLParser import HTMLParser # Python 2.6-2.7
except ImportError:
    from html.parser import HTMLParser # Python 3

"""
Ctrl-C per uscire.
"""

id_a = [1111111,2222222,3333333,4444444,5555555]

def get_cpuload():
    cpuload = subprocess.check_output('top -bn1 | grep "Cpu(s)" | sed "s/.*, *([0-9.]*)%* id.*/1/" | awk "{print 100 - $1'%'}"')
    return cpuload

def get_api(child):
    r = requests.get('http://meteoxxxxxxxxxxxxxxxxx.altervista.org/api.json')
    value = r.json()['stats']['current'][child]
    h = HTMLParser()
    value = h.unescape(value)
    return value

def get_ram():
    san = subprocess.check_output(['free','-m'])
    lines = san.split('n')
    return ( int(lines[1].split()[3]) )

def entities(frase):
    h = HTMLParser()
    return h.unescape(frase)

def get_cpu_temp():
    tempFile = open( "/sys/class/thermal/thermal_zone0/temp" )
    cpu_temp = tempFile.read()
    tempFile.close()
    temperatura = float(cpu_temp)/1000
    temperatura = str(temperatura) + "°C"
    h = HTMLParser()
    ritorno = h.unescape(temperatura)
    return ritorno

def get_gpu_temp():
    gpu_temp = commands.getoutput( '/opt/vc/bin/vcgencmd measure_temp' ).replace('temp=','').replace(''C','')
    return float(gpu_temp)

def get_connections():
    san = subprocess.check_output(['netstat','-tun'])
    return len([x for x in san.split() if x == 'ESTABLISHED'])

def get_ipaddress_ext():
    out = commands.getoutput( 'curl ipv4.icanhazip.com' )
    return out.split('n')[-1]

def get_ipaddress_int():
    arg='ip route list'
    ip=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
    data = ip.communicate()
    split_data = data[0].split()
    ipaddr = split_data[split_data.index('src')+1]
    return ipaddr

def get_uptime():
    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])
        uptime = (timedelta(seconds = uptime_seconds))
    return str(uptime).split('.')[0]

def handle(msg):
    chat_id = msg['chat']['id']
    command = msg['text']
    sender = msg['from']['id']
    print 'comando: %s' % command
   
    #if sender in id_a:
    if sender:
        if command == '/ciao':
            bot.sendMessage(chat_id, 'Hei, ciao!')
        elif command == '/status':
            #bot.sendMessage(chat_id, 'CPU ' + str(get_cpuload()) + '%')
            bot.sendMessage(chat_id, 'Temp.CPU ' + get_cpu_temp())
            bot.sendMessage(chat_id, 'Free RAM ' + str(get_ram()) + ' MB')
            bot.sendMessage(chat_id, 'IP int ' + str(get_ipaddress_int()))
            bot.sendMessage(chat_id, 'IP ext ' + str(get_ipaddress_ext()))
            bot.sendMessage(chat_id, 'Uptime ' + get_uptime())
        elif command == '/meteo':
            bot.sendMessage(chat_id, 'OutTemp: ' + get_api('outTemp'))
            bot.sendMessage(chat_id, 'Humidity: ' + get_api('humidity'))
            bot.sendMessage(chat_id, 'WindSpeed: ' + get_api('windSpeed'))
        elif command == '/reboot':
            if sender in id_a:
                bot.sendMessage(chat_id, 'Riavvio in corso...')
                os.system("sudo reboot")
            else:
                bot.sendMessage(chat_id, 'Not auth for the reboot ' + str(sender))
        else:
            bot.sendMessage(chat_id, 'Not auth ' + str(sender))
bot = telepot.Bot('000000000:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
bot.message_loop(handle)
print 'listening...'
while 1:
    time.sleep(100)
__________________________________________________________________

salvare lo script

provare lo script con
sudo python bot.py


sudo crontab -e
___________________________
aggiungere in fondo la riga

@reboot python /home/pi/bot.py &

 
 
 

RPi-Monitor

Post n°15 pubblicato il 24 Luglio 2017 da l30n1d4
 

sudo apt-get install apt-transport-https ca-certificates
sudo wget http://goo.gl/vewCLL -O /etc/apt/sources.list.d/rpimonitor.list
sudo apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 2C0D3C0F
sudo apt-get update && sudo apt-get install rpimonitor
sudo /usr/share/rpimonitor/scripts/updatePackagesStatus.pl

http://<ip_raspberry>:8888

 
 
 

weewx extension: weather monitoring weewx

Post n°14 pubblicato il 11 Luglio 2017 da l30n1d4
 

sudo apt-get install xtide xtide-data

cd /tmp

sudo wget http://lancet.mit.edu/mwall/projects/weather/releases/weewx-forecast-3.2.14.tgz

estrarre l'archivio in /tmp

cd ~/skins/

sudo cp /tmp/forecast-3.2.14/skins/compare compare

sudo cp /tmp/forecast-3.2.14/skins/forecast forecast

sudo chown -R $USER /home/weewx/skins/compare

sudo chown -R $USER /home/weewx/skins/forecast

wee_extension --install /tmp/weewx-forecast-3.2.14.tgz

sudo /etc/init.d/weewx restart

sudo tail -f /var/log/syslog

 

Documentazione: https://github.com/weewx/weewx/wiki/forecasting

 
 
 

Raspberry Pi Camera con aggiunta di messaggi timestamp e upload FTP (versione 2)

Post n°13 pubblicato il 18 Settembre 2015 da l30n1d4
 

crontab -e

---------------------------------------------

*/5 * * * * /home/pi/TakeAndUpload.sh

---------------------------------------------

mkdir /home/pi/images
sudo apt-get install ftp imagemagick

---------------------------------------------

#!/bin/bash


# Configure the vars in the following section

####################################################
##############  START CONFIGURATION  ###############
####################################################

ARGS="-vf -hf -w 1024 -h 720 -q 50 -n -ex auto"
ARGSLQ="-vf -hf -w 320 -h 240 -q 50 -n -ex auto"
DAT=$(date +"%m-%d-%Y")
ORA=$(date +"%H:%M")
TEXT_TOPLEFT="Prova"
TEXT_TOPRIGHT="Data:$DAT""_Ora:$ORA"
TEXT_BOTTOMLEFT="http://prova.org"
TEXT_BOTTOMRIGHT="(c)Mario_Rossi"
LOGO_TOPRIGHT="/home/pi/images/logo.png"

#FTP SETTINGS
HOST="ftpsite"
USER="user"
PASS="pass"
DIR="webcam"

#DATE AND LOG
dateTaken=$(date "+%d-%m-%Y-%H:%M")
now=$(date "+%H%M")
today=$(date "+%d%m%Y")
logfile="/home/pi/images/webcam_$today.log"

###############################################
##############  END CONFIGURATION  #################
###############################################

cd /home/pi/images
echo "###################################" >> $logfile
echo "starting script $dateTaken" >> $logfile
echo "Taking a Picture" >> $logfile

/opt/vc/bin/raspistill $ARGS -o /home/pi/images/image.jpg >> $logfile
/opt/vc/bin/raspistill $ARGSLQ -o /home/pi/images/current.jpg >> $logfile
echo "Convert and add overlays" >> $logfile

convert /home/pi/images/image.jpg
          -gravity NorthWest -background Blue -splice 0x18 -pointsize 17 -fill $
          -gravity NorthEast -fill yellow -annotate +0+0 $TEXT_TOPRIGHT
          -gravity SouthWest -background Blue -splice 0x18 -pointsize 15 -fill $
          -gravity SouthEast -fill yellow -annotate +0+0 $TEXT_BOTTOMRIGHT
          -gravity NorthEast $LOGO_TOPRIGHT -geometry +5+19 -composite
         /home/pi/images/big.jpg >> $logfile 2>&1

cputemp=$(/opt/vc/bin/vcgencmd measure_temp)
myip=$(curl --connect-timeout 10 http://ifconfig.me/ip)
uptime=$(uptime)
echo "LastUpdate: $dateTaken | CPU $cputemp | IP: $myip | uptime: $uptime" > /h$

echo "Upload big.jpg to FTP" >> $logfile
echo "Upload current.jpg to FTP" >> $logfile
# Start the FTP client

ftp -p -inv $HOST << EOF >> $logfile
user $USER $PASS
cd $DIR
put big.jpg
put current.jpg
put status.txt
bye
EOF
mv -f /home/pi/images/current.jpg /home/pi/images/old/img_$dateTaken.jpg
echo "Remove big.jpg" >> $logfile
rm -f /home/pi/images/big.jpg
echo "Remove image.jpg" >> $logfile
rm -f /home/pi/images/image.jpg
echo "Ok"

 
 
 

Raspberry Pi Camera con aggiunta di messaggi timestamp e upload FTP

Post n°12 pubblicato il 30 Marzo 2014 da l30n1d4
 

Per abilitare la raspberry pi camera:

sudo raspi-config

Abilitare la camera, salvare e riavviare. Poi:

sudo apt-get update

Installare il programma per la modifica delle foto con:

sudo apt-get install imagemagick

Installare wput per trasferire in automatico l'immagine su un server ftp (opzionale) con:

sudo apt-get install wput

Creare uno script con:

sudo nano /etc/init.d/shot.sh

Incollare il seguente semplice codice che fà uso di raspistill:

#!/bin/sh

OPTIONS='-w 1024 -h 768 -q 80 -x'

DATE=$(date +"%d/%m/%Y")

HOUR=$(date +"%R")

cd /home/pi

raspistill -o big.jpg $OPTIONS

sleep 1

raspistill -o current.jpg -w 200 -h 150 -q 80 -x

sleep 1

convert big.jpg -pointsize 14 -fill white -annotate +670+590 $DATE -pointsize 14 -fill white -annotate +974+758 $HOUR -pointsize 14 -fill white -annotate +10+758 "INSERIRE_UN_MESSAGGIO_QUI" big.jpg

wput current.jpg ftp://USER:PASSWORD@TUO_SITO_FTP

wput big.jpg ftp://USER:PASSWORD@TUO_SITO_FTP

Questo script crea ed invia al server FTP due immagini: una piccola per il preview ed una grande con le dimensioni descritte nella variabile OPTIONS.

Rendiamo lo script eseguibile con:

sudo chmod 755 /etc/init.d/shot.sh

Impostiamo lo script che parta all'avvio con:

sudo update-rc.d shot.sh defaults

Impostiamo ora un job cron con:

crontab -e

Incollare il seguente semplice codice che ogni mezzora dalle 06:00 alle 22:00 esegue il precedente script:

*/30 6-22 * * * pi /etc/init.d/shot.sh

Salviamo e riavviamo il raspberry.

 
 
 

Installazione di WeeWX per stazione meteo PCE-FWS 20

Post n°11 pubblicato il 30 Marzo 2014 da l30n1d4
 

Iniziamo con:

sudo raspi-config

espandere sd

overclock 900mhz

split memoria 16mb

riavviare


sudo apt-get update

sudo adduser weewx

sudo usermod -a -G sudo weewx

exit

riconnettersi con le credenziali dell user weewx sempre via SSH e poi installare le dipendenze:

sudo apt-get install -y python-configobj python-cheetah python-imaging python-serial python-usb mysql-client python-mysqldb python-dev ftp python-pip

sudo pip install pyephem

wget http://downloads.sourceforge.net/project/weewx/weewx-2.6.2.tar.gz

tar -xvf weewx-2.6.2.tar.gz

cd weewx-2.6.2

./setup.py build

sudo ./setup.py install

sudo nano /home/weewx/weewx.conf

cambiare le impostazioni riferite a latitudine e longitudine ed altezza in base alla locazione della vostra stazione meteo. Cambiare anche il tipo di stazione e mettere FineOffsetUSB

sudo apt-get install apache2

cd /var/www

sudo ln -s /home/weewx/public_html meteo

cd /home/weewx

sudo cp util/init.d/weewx.debian /etc/init.d/weewx

sudo chmod +x /etc/init.d/weewx

sudo update-rc.d weewx defaults 98

sudo /etc/init.d/weewx start

bene, aspettare 10 minuti che il programma inizi a registrare i primi dati e dopo sarà visibile la pagina: http://IP_DEL_RASPBERRY/meteo/

 
 
 

vsFTPd

Post n°10 pubblicato il 15 Febbraio 2014 da l30n1d4
 

Per realizzare un server FTP che punti (anche) alla nostra cartella downloads in cui scarica transmission procederemo così:

sudo apt-get update

sudo apt-get install vsftpd

Editiamo il file di configurazione con:

sudo nano /etc/vsftpd.conf

Applichiamo i seguenti cambiamenti:

anonymous_enable=YES lo cambiamo in: anonymous_enable=NO

togliamo # (commento) da local_enable=YES e write_enable=YES

scriviamo in fondo al file: force_dot_files=YES

Usciamo con CTRL+X, salviamo e riavviamo il servizio con:

sudo service vsftpd restart

Creiamo il collegamento nella home alla nostra cartella in cui scarica transmission con:

ln -s /media/usb0/transmission/downloads/ ~/HardDisk

 
 
 

Webmin

Post n°9 pubblicato il 13 Febbraio 2014 da l30n1d4
 
Tag: webmin

Per installare webmin (un frontend HTTP) per poter controllare ed avere maggiori informazioni sul nostro raspberry pi, procederemo così:

sudo apt-get update

sudo apt-get install -y perl libnet-ssleay-perl openssl libauthen-pam-perl libpam-runtime libio-pty-perl apt-show-versions python

wget http://prdownloads.sourceforge.net/webadmin/webmin_1.670_all.deb

sudo dpkg --install webmin_1.670_all.deb

A questo punto, dopo che si sarà installato webmin (occorrono una manciata di minuti per scompattare l'archivio), webmin sarà raggiungibile all'indirizzo: https://ip_del_raspberry_pi:10000/ e con USER e PASS uguali a chi posside le credenziali di root (default user=pi pass=raspberry).

 
 
 

Munin: statistiche e grafici

Post n°8 pubblicato il 20 Novembre 2013 da l30n1d4
 

Per avere un resoconto dettagliato del proprio sistema raspberry si può utilizzare munin. Esso si compone di due parti: il server che crea i grafici e il nodo che invia i dati. Siccome vogliamo che il raspberry crei i grafici autonomamente, installeremo entrambi.

NOTA: si presuppone che prima sia installato apache e php (vedi post).

sudo apt-get update

sudo apt-get install munin munin-node

sudo mkdir /var/www/munin

sudo chown munin:munin /var/www/munin

sudo nano /etc/munin/munin.conf

Modificare il file togliendo il commento davanti (#):

htmldir /var/www/munin

Salvare ed uscire, editare il file:

sudo nano /etc/munin/apache.conf

Modificare il file come segue:

Alias /munin /var/www/munin

....

<Directory /var/www/munin>
        Order allow,deny
        Allow from all
        Options None

Salvare, uscire e riavviare il sistema con:

sudo reboot

Ci vogliono 5 minuti prima che la pagina http://ip_raspberry_pi/munin/ sia attiva perchè stà creando i grafici.

 
 
 
Successivi »
 

AREA PERSONALE

 

TAG

 

ARCHIVIO MESSAGGI

 
 << Aprile 2024 >> 
 
LuMaMeGiVeSaDo
 
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          
 
 

CERCA IN QUESTO BLOG

  Trova
 
 
 
 

© Italiaonline S.p.A. 2024Direzione e coordinamento di Libero Acquisition S.á r.l.P. IVA 03970540963