Subida de archivos

This commit is contained in:
Sergio Pernas 2022-02-23 11:42:32 -03:00
commit d9963a7ddd
13 changed files with 329 additions and 0 deletions

74
bin/nodemecu Normal file
View file

@ -0,0 +1,74 @@
#!/bin/bash
if [ $UID -ne 0 ]; then
echo "Ejecute 'sudo $0'"
exit
fi
# LECTURA FICHERO DE CONFIGURACION
config=/etc/nodemecu.conf
source $config
[ -z $1 ] && exit
com=$1
case $com in
start)
if [ -z $interval ]; then
echo "Asegurese de haber establecido 'intervalo' de regitro y envio de datos."
exit 1
fi
if [ -z $name ]; then
echo "Asegurese de haber establecido el 'nombre' de dispositivo."
exit 1
fi
echo "El modo de operación es '$mode', puede cambiar el modo con el comando:"
echo "'nomecu modo MODE' donde 'MODE' puede ser 'test' para generar y enviar datos simulados o 'sensores' para enviar datos tomados de los sensores."
echo ""
read -p "Desea continuar? Presione 'enter' para continuar o 'ctrl-c' para cancelar..."
echo "*/$interval * * * * /opt/nodemecu/data_gen.sh" > /tmp/nodemecu.crontab
crontab -u root /tmp/nodemecu.crontab
echo ""
echo "Se enviarán datos cada $interval minutos."
echo ""
exit
;;
stop)
crontab -u root -r
echo "Se detuvo la toma y envio de datos."
echo ""
;;
intervalo)
if [[ $1 == intervalo && $2 -ge 1 && $2 -le 60 ]]; then
sed -i 's/interval=[0-9]*/interval='$2'/' $config
echo "intervalo seteado en $2"
exit
else
echo "Establezca un valor entre 1 y 60."
exit 1
fi
;;
nombre)
parametros=$*
nombre=$(echo $parametros | sed 's/nombre //g' | sed 's/ /_/g')
if [[ "$nombre" =~ ^[a-zA-Z0-9_]+$ ]];then
sed -i 's/name=[a-z A-Z 0-9]*/name='"$nombre"'/' $config
else
echo "El nombre solo puede contener carateres alfanumericos."
fi
;;
monitor)
$install_dir/monitor.sh
;;
*)
exit
;;
esac

4
bin/reset Normal file
View file

@ -0,0 +1,4 @@
rm stack/*
rm historical/*
printf "" > errors.log
printf "0" > counter

34
controller.py Executable file
View file

@ -0,0 +1,34 @@
#!/usr/bin/env python
import time
import serial
import sys
ser = serial.Serial(
port='/dev/serial0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
baudrate = 14400,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
ser.flush()
cw = int(sys.argv[1], 0)
com = [cw]
ser.write(serial.to_bytes(com))
ser.flush()
while True:
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8', errors='replace').rstrip()
time.sleep(0.5)
print(line)
ser.flush()
break
quit()

1
counter Normal file
View file

@ -0,0 +1 @@
0

53
data_gen.sh Executable file
View file

@ -0,0 +1,53 @@
#!/bin/bash
source /etc/nodemecu.conf
case $mode in
test)
lecturas="id:dummy_plug-01 ts:$(date +%s) tp:temp vl:$(( $RANDOM % 20 + 15 )) un:C er:99 AD_SENSOR ts:$(date +%s) tp:hum vl:$(( $RANDOM % 50 + 35 )) un:percent er:99 AD_ARDUINO id:dummy_plug-02 ts:$(date +%s) tp:temp vl:$(( $RANDOM % 20 + 15 )) un:C er:99 AD_SENSOR ts:$(date +%s) tp:hum vl:$(( $RANDOM % 50 + 35 )) un:percent er:99 AD_ARDUINO id:dummy_plug-03 ts:$(date +%s) tp:temp vl:$(( $RANDOM % 20 + 15 )) un:C er:99 AD_SENSOR ts:$(date +%s) tp:hum vl:$(( $RANDOM % 50 + 35 )) un:percent er:99 AD_ARDUINO id:dummy_plug-04 ts:$(date +%s) tp:temp vl:$(( $RANDOM % 20 + 15 )) un:C er:99 AD_SENSOR ts:$(date +%s) tp:hum vl:$(( $RANDOM % 50 + 35 )) un:percent er:99 END"
;;
esac
for i in $lecturas;do
case $i in
id*)
sensores="$sensores { $(echo \"id\":\"$(echo $i | cut -d ":" -f 2)\", \"sensores\": [ )"
;;
ts*)
sensores="$sensores { $(echo \"timestamp\": $(echo $i | cut -d ":" -f 2),)"
;;
tp*)
sensores="$sensores $(echo \"type\": \"$(echo $i | cut -d ":" -f 2)\",)"
;;
vl*)
sensores="$sensores $(echo \"value\": $(echo $i | cut -d ":" -f 2),)"
;;
un*)
sensores="$sensores $(echo \"unit\": \"$(echo $i | cut -d ":" -f 2)\",)"
;;
er*)
sensores="$sensores $(echo \"error\": $(echo $i | cut -d ":" -f 2) })"
;;
AD_SENSOR)
sensores="$sensores,"
;;
AD_ARDUINO)
sensores="$sensores]},"
;;
END)
sensores="$sensores]}"
;;
esac
done
counter=$(cat $install_dir/counter)
uuid="$(uuidgen)"
timestamp="$(date +%s)"
json="{\"transaction_uuid\":\"$uuid\",\"controller_id\":\"$name\",\"timestamp\":\"$timestamp\",\"error_code\":\"10\",\"coordinates\":{\"lat\":1,\"lng\":1},\"battery_status\":\"98\",\"sample\":\"0\",\"storage\":\"uso del almacenamiento\",\"arduinos\":[$sensores]}"
touch /opt/nodemecu/lock
file=$(date +%Y%m%d%H%M%S)-$(uuidgen)
for ((i=1 ; i <=3 ; i++));do
if echo $json | jsonlint-php 2> /dev/null;then
echo $json > /opt/nodemecu/stack/$file && rm /opt/nodemecu/lock && echo $((counter+1)) > $install_dir/counter && break
else
echo "$(date +%Y-%m-%d-%H:%M:%S) - No se pudo obtener información." >> /opt/nodemecu/errors.log && sleep 1
fi
done

10
functions Normal file
View file

@ -0,0 +1,10 @@
get_stack () {
if [[ ! -z $1 && $1 == "wc" ]];then
ls /opt/nodemecu/stack | wc -l
else
ls /opt/nodemecu/stack | tail -1
fi
}

42
install.sh Executable file
View file

@ -0,0 +1,42 @@
#!/bin/bash
files="data_gen.sh monitor.sh register.sh uninstall.sh monitor.web bin functions counter"
config=nodemecu.conf.sample
source $config
echo -e "1. Instalando dependencias"
#sudo apt update && sudo apt install -y jq uuid-runtime dnsmasq dnsutils
sudo pip install pyserial
echo ""
# Estructura de directorios
echo -e "2. Creando directorios y copiando archivos"
sudo mkdir -vp $install_dir/archives/historical
sudo mkdir -vp $install_dir/archives/logs
sudo mkdir $historical
sudo mkdir $stack
echo ""
sudo cp -vr $files $install_dir
sudo cp -v $config /etc/nodemecu.conf
sudo ln -s $install_dir/bin/nodemecu /usr/bin/nodemecu
sudo touch $log
echo ""
echo "3. Configurando systemd"
sudo cp nodemecu.service /lib/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable nodemecu.service
sudo systemctl start nodemecu.service
sudo systemctl status nodemecu.service
echo ""
echo ". Alias de comandos."
echo "alias nodemecu='sudo nodemecu'" >> $HOME/.bashrc
echo ""
echo "Ejecute 'source ~/.bashrc' para aplicar los cambios."
echo ""

16
monitor.sh Executable file
View file

@ -0,0 +1,16 @@
#!/bin/bash
source /etc/nodemecu.conf
while :;do
clear
echo "$(date)"
echo "Stack: $(ls $stack | wc -l) ficheros"
echo "Historicos: $(ls $historical | wc -l) ficheros"
echo "Testigo: $(cat $install_dir/counter)"
echo "Errores: $(wc -l $log) registros"
echo "Ultimo error registrado:"
tail -1 $log
echo ""
echo "'ctrl-c' para salir."
sleep 100
done

11
monitor.web Executable file
View file

@ -0,0 +1,11 @@
#!/bin/bash
source /etc/nodemecu.conf
echo "<p>$(date)<br>"
echo "Stack: $(ls $stack | wc -l) ficheros<br>"
echo "Historicos: $(ls $historical | wc -l) ficheros<br>"
echo "Testigo: $(cat $install_dir/counter)<br>"
echo "Errores: $(wc -l $log) registros<br>"
echo "Ultimos errores registrados<br>"
tail -1 $log
echo "<br></p>"

16
nodemecu.conf.sample Normal file
View file

@ -0,0 +1,16 @@
url=https://ectomobile.sutty.nl/transactions
name=
interval=
mode=test
# AJUSTES GENERALES
# SE RECOMIENDA NO MODIFICAR ESTAS LINEAS
curl_err=/tmp/curl_err
historical_file_size=1440
logs_file_size=1440
install_dir=/opt/nodemecu
stack=$install_dir/stack
historical=$install_dir/historical
log=$install_dir/errors.log
corrupt=$install_dir/corrupt

8
nodemecu.service Normal file
View file

@ -0,0 +1,8 @@
[Unit]
Description=Procesador de pila y transmisor de datos Nodemecu.
[Service]
ExecStart=/opt/nodemecu/register.sh
[Install]
WantedBy=multi-user.target

47
register.sh Executable file
View file

@ -0,0 +1,47 @@
#!/bin/bash
#set -e
source /etc/nodemecu.conf
source /opt/nodemecu/functions
# Revisando stack
for filename in /opt/nodemecu/stack/*;do
test "$filename" = "/opt/nodemecu/stack/\*" || break
jsonlint-php $filename > /dev/null || mv -v $filename $corrupt
done
while :;do
ping -c 1 fsf.org > /dev/null 2>&1 || continue
test_url="$(curl -s -X POST -o /dev/null -w "%{http_code}" $url)"
if [ $test_url -eq 404 ];then
echo "$(date +%Y-%m-%d-%H:%M:%S) - $url - $test_url" >> /opt/nodemecu/errors.log && sleep 300 && continue
fi
[ -f $install_dir/lock ] && continue
file=$(get_stack)
[ -z $file ] && continue
local_transaction_uuid=$(jq -r '."transaction_uuid"' $stack/$file)
remote_transaction=$(curl -s --connect-timeout 0,9 --show-error -w "~%{http_code}" -X POST -H "Content-Type: application/json" -d @$stack/$file $url 2> $curl_err)
remote_response="$(echo $remote_transaction | cut -d '~' -f 1)"
server_error="$(echo $remote_transaction | cut -d '~' -f 2)"
if [ ${#remote_response} -eq 36 ];then
if [ $local_transaction_uuid == $remote_response ]; then
mv $stack/$file $historical
echo -e "$remote_response: \e[92mOK\e[0m"
fi
else
echo -e "$local_transaction_uuid: \e[91mFAIL\e[0m"
# errores
unset srv_msg
unset curl_msg
err_time=$(date +%Y-%m-%d-%H:%M:%S)
[ ! -z "$remote_response" ] && srv_msg="- $( echo $remote_response | grep -o '<body.*>.*</body>')"
[ -s "$curl_err" ] && curl_msg="- $(</tmp/curl_err)"
echo $err_time - $local_transaction_uuid - server status: $server_error $srv_msg $curl_msg >> $log
rm $curl_err
fi
done
exit

13
uninstall.sh Executable file
View file

@ -0,0 +1,13 @@
#!/bin/bash
sudo rm /etc/nodemecu.conf
sudo rm /usr/bin/nodemecu
sudo crontab -u root -r
sudo rm -rf /opt/nodemecu/
sed -i '/*sudo nodemecu*/d' $HOME/.bashrc
sudo rm /lib/systemd/system/nodemecu.service
sudo systemctl stop nodemecu.service
sudo systemctl disable nodemecu.service
sudo systemctl daemon-reload