/** **/

ITСooky

IT-рецепты съедобные и не очень!

DCPD — дубликатор флешек и копир на SATA HDD, с доступом к файлам по Wi-Fi, на Node-Red и Raspberry Pi 4!

дата 25.06.2020

Сегодня буду делать классический DCPD — Dooms Content Party Device термин придумал только-что может приживется! Это устройство для оффлайн Wi-Fi интернета, способ доставки контента USB флешка. Оффлайн интернет на Кубе (Иране, Китае) работает чрез передачу жестких дисков и подключения оных к пк, но гораздо удобнее было бы подключаться по Wi-Fi.

Как это будет работать:
1. Заходим на Wi-Fi сеть itcooky которую создает DCPD
2. Заходим в меню DCPD по адресу http://10.100.10.1:1880/ui
3. Подключаем флешку к DCPD, через меню копируем её на внутренний HDD

4. Делимся HDD или флешкой, тоже через web меню!
5. Выключаем DCPD тоже через меню, надо дождаться на корпусе когда зеленый огонек перестанет мигать, и можо до упора нажимать большую кнопку и ждать пока не выключится!

В основе будет Raspberry Pi 4, но потребуется еще куча железа!

Шилды хорошо продуманны, вставляются в корпус вот таким бутербродом — но доступа к SD малинки нет!

Беру X825 2.5″ SATA HDD/SSD Shield и X735 V2.1 Power Management Board! Их надо подключать как показано на картинках на сайте — получается что питание идет по разъемы 5v OUT — а сначала подключал к 5v IN на шильде с вентилятором — не сгорело но и не работало!




ОСТРОЖНО: X825 при задействовании USB создает такие помехи что перестает работать Wi-Fi 2,4Hz на Малинке! Производители шильда советуют включать 5Hz Wi-Fi или лучше вообще его не использовать!!!

От производителя:
We found that USB 3.0 high-speed transmission will interfere with the Raspberry Pi’s 2.4G wifi signal. So when install the pi in the case, if you find the 2.4G signal is unstable, please try to use WIFI 5G AP. (Please refer to WiKi)
We think this is caused by the unreliability of the Raspberry Pi’s wifi design. If the Raspberry Pi Foundation reserves the SMA IPEX antenna interface, everything will become easier. We will also struggle to solve this issue in the future.

Кстати X735 V2.1 Power Management Board брать совсем не обязательно — можно и без него собрать!




Блок питания нужен на 4А уменя вот такой!

Корпус по типа этого Geekworm Raspberry Pi 4 X825 Metal Case+Power Switch+Cooling Fan, Honeycomb Chassis Support X825 2.5 inch SATA SSD/HDD Shield & Raspberry Pi 4 Model B & X735





Винтиков с корпусом приходит мало, пришлось добирать нужный крепеж! Кнопка одно нажатие — включить, долгое нажатие — выключить! X825 подключается через USB переходник, DC power разьем на X735 я закляил, чтобы случайно не воткнуть — но вообще-то usb разъемы на этом шильде, тоже все для питания!

Надо ставить Raspberry Pi OS (32-bit) Lite (ранее известный как Raspbian) в этой версии нет Desktop окружения.

Качаю её тут www.raspberrypi.org/downloads/raspbian/
А вот тут качаю установщик https://www.raspberrypi.org/downloads/

Чтобы ssh работал, на карте в BOOT разделе надо сделать файл с именем ssh и оно после этого будет работать. После этого можно карту вставлять в малинку, подключать ethernet кабель, включать и смотреть какой малинка получила IP я посмотрел на роутере, можно и на малинку руками зайти и посмотреть коммандой
ifconfig

Имя: pi
пароль: raspberry

Посмотрю что у меня за модель
cat /sys/firmware/devicetree/base/model

Raspberry Pi 4 Model B Rev 1.2

Посмотрим сколько памяти
free -h

              total        used        free      shared  buff/cache   available
Mem:          3.8Gi        90Mi       3.5Gi       8.0Mi       242Mi       3.6Gi
Swap:          99Mi          0B        99Mi

о 4Gb!

Обновляюсь, всегда полезно
sudo apt update
sudo apt full-upgrade

У меня SATA HDD форматирован в ext4 если у вас ntfs надо установить
sudo apt-get install ntfs-3g

Делаю для него директорию и монтирую
sudo mkdir /mnt/hdd
sudo mount /dev/sda1 /mnt/hdd

Проверяю чистую скорость HDD — пишет файлд созданный системой!
sudo dd if=/dev/zero of=test.file count=10000 bs=1048576

Показывает фантастические 100 MB/ гораздо выше чем у USB флешки — глюк какойто!

10485760000 bytes (10 GB, 9.8 GiB) copied, 104.358 s, 100 MB/s

Копирую файл на флешку
pv /mnt/hdd/test.file > /mnt/usb1/test.file

Получаю типичные скорости для флешки — значит новейшая флешка гораздо медленнее старого HDD тоже подключенного по USB3

9.77GiB 0:07:18 [22.8MiB/s] [================================>] 100%

Монтируем хард на загрузке
Для этого посмотрим дополнительную информацию
sudo blkid
ищем по вторичным признаком наш HDD

/dev/sda1: UUID="289717cc-b3ec-4f12-9ae5-318b52a57a22" TYPE="ext4" PARTUUID="90909090-01"

я его первым подключил, он первым sda и оказался

ВНИМАНИЕ: Автоматическое монтирование USB на загрузке в Raspberry не работает!

Официальный способ
www.raspberrypi.org/documentation/configuration/external-storage.md
добавляю строчку в
sudo vi /etc/fstab
такую

UUID=289717cc-b3ec-4f12-9ae5-318b52a57a22 /mnt/hdd ext4 defaults,noatime,auto 0 0

НЕ РАБОТАЕТ

Тут много страдальцев по той же теме
www.raspberrypi.org/forums/viewtopic.php?f=28&t=9949

Короткое время работало вот так
Чтобы все таки примонтировалось на загрузки надо в cron
sudo crontab -e
добавить вот такую конструкцию

@reboot root  /bin/bash -c 'sleep 10 &&sudo /bin/mount -U 289717cc-b3ec-4f12-9ae5-318b52a57a22 /mnt/hdd'

потом НЕ РАБОТАЛО

Монтировать на загрузке будут через запуск команды из Node-Red — буквально одна ниточка — исполнять раз при старте, запустить hdd_m.sh!

Делаем из Малинки точку доступа Wi-Fi
Все прекрасно описано вот тут https://learn.sparkfun.com/tutorials/setting-up-a-raspberry-pi-3-as-an-access-point/all для RPI4 надо толко еще одну команду добавить!

Однако сначала надо обновиться а то не ставится
sudo apt-get update
sudo apt install dnsmasq hostapd

все равно не ставится, ставлю так
sudo apt install dnsmasq hostapd --fix-missing

Поставилось, дальше много чего редактруем
sudo vi /etc/dhcpcd.conf
Добавляю

denyinterfaces wlan0

sudo vi /etc/network/interfaces
Добавляем

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

allow-hotplug wlan0
iface wlan0 inet static
    address 10.100.10.1
    netmask 255.255.255.0
    network 10.100.10.0
    broadcast 10.100.10.255

sudo vi /etc/hostapd/hostapd.conf
Добавляем

interface=wlan0
driver=nl80211
ssid=Itcooky
hw_mode=a
channel=40
ieee80211n=1
wmm_enabled=1
ht_capab=[HT40][SHORT-GI-20][DSSS_CCK-40]
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_key_mgmt=WPA-PSK
wpa_passphrase=QWErty123
rsn_pairwise=CCMP

Тут настройки по 5Hz Wi-fi. Канал я взял посмотрев сначали — каике есть вот так
iw list

sudo vi /etc/default/hostapd
Добавляем

DAEMON_CONF="/etc/hostapd/hostapd.conf"

sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.bak
sudo vi /etc/dnsmasq.conf

Добавляем

interface=wlan0 
listen-address=10.100.10.1
bind-interfaces 
server=8.8.8.8
#address=/#/10.100.10.1
domain-needed
bogus-priv
dhcp-range=10.100.10.10,10.100.10.250,24h

Выполняем
sudo systemctl start dnsmasq
sudo systemctl unmask hostapd
sudo systemctl enable hostapd
sudo systemctl start hostapd

И для RPI4 надо еще
sudo rfkill unblock wlan
Помотрим перестало ли блокироваться
sudo rfkill list

Перегружаемся
sudo reboot

Как завелся AP можно посмотреть набрав
sudo service hostapd status

Ставим NGINX
Надо просто запустить установку
sudo apt install nginx
и сам
sudo /etc/init.d/nginx start

Файлы страниц лежат тут
cd /var/www/html
идем туда
делаю папку
sudo mkdir ./data
и делаю страничку
vi index.html
с таким текстом

<!DOCTYPE html>
<html>
<head>
<title>Welcome DCPD!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
                                              
Files are available at <a href="./data"> this folder</a><br> 

</body>
</html>

ничего особенного просто ссылка на data

редактирую сайт с настройками nginx
sudo vi /etc/nginx/sites-available/default
доводим кусочек с location до такого вида

location / {
try_files $uri $uri/ =404;
autoindex on;
sendfile on;
tcp_nopush on;
}

autoindex точно нужен, остальное тоже советуют

пере нгинкс
sudo service nginx reload

Ставим Node Red
Для RPI есть способ от самих красных
https://nodered.org/docs/getting-started/raspberrypi

Надо только выпонить
bash <(curl -sL https://raw.githubusercontent.com/node-red/linux-installers/master/deb/update-nodejs-and-nodered)
И чтобы само грузилось
sudo systemctl enable nodered.service

И все, заходим на http://ваш_ip4:1880 и делаем что хотим

В самом Node-Red надо установить node-red-dashboard

DCPD на или в Node-red
Картинка со всеми кирпичами

И кодом

[{"id":"b44d7514.83389","type":"tab","label":"Flow 1","disabled":false,"info":""},{"id":"54fb509b.2c2ed","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/first_m.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":650,"y":160,"wires":[["becfcd98.7c18f"],[],[]]},{"id":"e32b03af.b293f","type":"ui_text","z":"b44d7514.83389","group":"7f5c3aa5.c49854","order":1,"width":0,"height":0,"name":"","label":"Size of data:","format":"{{msg.payload}}Mb","layout":"row-left","x":1430,"y":160,"wires":[]},{"id":"58b931c3.744ac8","type":"ui_button","z":"b44d7514.83389","name":"","group":"7f5c3aa5.c49854","order":3,"width":3,"height":1,"passthru":false,"label":"Mount","tooltip":"","color":"","bgcolor":"","icon":"","payload":"","payloadType":"str","topic":"","x":410,"y":160,"wires":[["54fb509b.2c2ed"]]},{"id":"4de280ba.95e15","type":"switch","z":"b44d7514.83389","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"asize","vt":"str"},{"t":"cont","v":"label","vt":"str"}],"checkall":"true","repair":false,"outputs":2,"x":1010,"y":200,"wires":[["cea5bb16.b5a5a8"],["cedce86d.2aa818"]]},{"id":"cea5bb16.b5a5a8","type":"split","z":"b44d7514.83389","name":"","splt":"#","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1150,"y":180,"wires":[["e32b03af.b293f"]]},{"id":"284f5a3e.56b85e","type":"ui_text","z":"b44d7514.83389","group":"7f5c3aa5.c49854","order":2,"width":0,"height":0,"name":"","label":"Label:","format":"{{msg.payload}}","layout":"row-left","x":1450,"y":220,"wires":[]},{"id":"cedce86d.2aa818","type":"split","z":"b44d7514.83389","name":"","splt":"#","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1150,"y":220,"wires":[["284f5a3e.56b85e"]]},{"id":"becfcd98.7c18f","type":"split","z":"b44d7514.83389","name":"","splt":";","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":890,"y":200,"wires":[["4de280ba.95e15"]]},{"id":"54348537.5cdffc","type":"ui_button","z":"b44d7514.83389","name":"","group":"7f5c3aa5.c49854","order":4,"width":3,"height":1,"passthru":false,"label":"Un mount","tooltip":"","color":"","bgcolor":"","icon":"","payload":"","payloadType":"str","topic":"","x":420,"y":240,"wires":[["e2c3bf55.06fee"]]},{"id":"e2c3bf55.06fee","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/first_unm.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":660,"y":240,"wires":[["becfcd98.7c18f"],[],[]]},{"id":"826e7da6.89bc","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/second_m.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":660,"y":440,"wires":[["5ca805f5.1e5734"],[],[]]},{"id":"ee6a802b.3ad798","type":"ui_text","z":"b44d7514.83389","group":"ec3ace8.c36b93","order":4,"width":0,"height":0,"name":"","label":"Free size:","format":"{{msg.payload}}Mb","layout":"row-left","x":1740,"y":440,"wires":[]},{"id":"baa5392d.c28648","type":"ui_button","z":"b44d7514.83389","name":"","group":"ec3ace8.c36b93","order":6,"width":3,"height":1,"passthru":false,"label":"Mount","tooltip":"","color":"","bgcolor":"","icon":"","payload":"","payloadType":"str","topic":"","x":110,"y":480,"wires":[["44a7e2f8.c28bcc"]]},{"id":"bda8585a.0472e8","type":"switch","z":"b44d7514.83389","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"asize","vt":"str"},{"t":"cont","v":"label","vt":"str"}],"checkall":"true","repair":false,"outputs":2,"x":1430,"y":500,"wires":[["6b20dc3b.1afd9c"],["ce94c5f1.65b9b"]]},{"id":"6b20dc3b.1afd9c","type":"split","z":"b44d7514.83389","name":"","splt":"#","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1590,"y":440,"wires":[["ee6a802b.3ad798"]]},{"id":"ce94c5f1.65b9b","type":"split","z":"b44d7514.83389","name":"","splt":"#","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1570,"y":560,"wires":[["9c6e90db.4c53d"]]},{"id":"bc7259c4.a27fd","type":"split","z":"b44d7514.83389","name":"","splt":";","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1290,"y":500,"wires":[["bda8585a.0472e8"]]},{"id":"3592ca8.0bf7db6","type":"ui_button","z":"b44d7514.83389","name":"","group":"ec3ace8.c36b93","order":5,"width":3,"height":1,"passthru":false,"label":"Un mount","tooltip":"","color":"","bgcolor":"","icon":"","payload":"","payloadType":"str","topic":"","x":120,"y":680,"wires":[["53cc1acc.29cfa4"]]},{"id":"692f75d5.160f24","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/second_unm.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":670,"y":600,"wires":[["bc7259c4.a27fd"],[],[]]},{"id":"154aa879.197de","type":"ui_button","z":"b44d7514.83389","name":"","group":"2fa9608d.2ce59","order":1,"width":0,"height":0,"passthru":false,"label":"Start copy","tooltip":"","color":"","bgcolor":"","icon":"","payload":"reset","payloadType":"str","topic":"","x":120,"y":880,"wires":[["2350a3d8.a3042c"]]},{"id":"611d713d.726e48","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/copytousb.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":660,"y":840,"wires":[["44ed3481.f21c14"],[],[]]},{"id":"9abe71d5.48763","type":"ui_text","z":"b44d7514.83389","group":"2fa9608d.2ce59","order":2,"width":0,"height":0,"name":"","label":"","format":"Coping to folder /{{msg.payload}}","layout":"row-left","x":1490,"y":800,"wires":[]},{"id":"fdd997bc.69107","type":"ui_gauge","z":"b44d7514.83389","name":"","group":"2fa9608d.2ce59","order":3,"width":6,"height":5,"gtype":"donut","title":"","label":"%","format":"{{value}}","min":0,"max":"100","colors":["#d1de24","#27eb20","#96002e"],"seg1":"","seg2":"","x":1490,"y":900,"wires":[]},{"id":"7ee0395c.eba5b","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/speedtousb.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":660,"y":780,"wires":[["fdd997bc.69107","a0ec9eaa.97de38"],[],[]]},{"id":"5ca805f5.1e5734","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/second_i.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":1020,"y":400,"wires":[["bc7259c4.a27fd"],[],[]]},{"id":"207aabab.8d4fc4","type":"inject","z":"b44d7514.83389","name":"","topic":"null on start","payload":" ","payloadType":"str","repeat":"","crontab":"","once":true,"onceDelay":0.1,"x":290,"y":60,"wires":[["e32b03af.b293f","284f5a3e.56b85e","ee6a802b.3ad798","fdd997bc.69107","9abe71d5.48763","9c6e90db.4c53d","784ef6f.b469208","692f75d5.160f24","e2c3bf55.06fee","b1afc99b.13cf3","b9d1c272.195b7"]]},{"id":"7fd33d21.b6d0dc","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/rpitemp.sh","addpay":true,"append":"","useSpawn":"false","timer":"","oldrc":false,"name":"","x":650,"y":1260,"wires":[["3ad9aa64.4a2d8e","d640f229.9bb7d8"],[],[]]},{"id":"3ad9aa64.4a2d8e","type":"ui_text","z":"b44d7514.83389","group":"2fa9608d.2ce59","order":4,"width":0,"height":0,"name":"","label":"Rpi4","format":"{{msg.payload}}","layout":"row-left","x":1030,"y":1260,"wires":[]},{"id":"3b1fe249.a09c66","type":"inject","z":"b44d7514.83389","name":"","topic":"","payload":"","payloadType":"date","repeat":"5","crontab":"","once":false,"onceDelay":0.1,"x":290,"y":1260,"wires":[["7fd33d21.b6d0dc"]]},{"id":"a0ec9eaa.97de38","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/sizeusb2.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":1020,"y":760,"wires":[["6b20dc3b.1afd9c"],[],[]]},{"id":"44ed3481.f21c14","type":"switch","z":"b44d7514.83389","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"pathonusb","vt":"str"}],"checkall":"true","repair":false,"outputs":1,"x":1110,"y":840,"wires":[["2ed432f3.bb44be"]]},{"id":"2ed432f3.bb44be","type":"split","z":"b44d7514.83389","name":"","splt":"#","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1250,"y":840,"wires":[["9abe71d5.48763"]]},{"id":"784ef6f.b469208","type":"ui_switch","z":"b44d7514.83389","name":"","label":"Change device","tooltip":"","group":"ec3ace8.c36b93","order":1,"width":4,"height":1,"passthru":false,"decouple":"false","topic":"","style":"","onvalue":"USB","onvalueType":"str","onicon":"","oncolor":"","offvalue":"HDD","offvalueType":"str","officon":"","offcolor":"","x":140,"y":340,"wires":[["a31b3fd4.9cc7f8"]]},{"id":"a31b3fd4.9cc7f8","type":"ui_text_input","z":"b44d7514.83389","name":"","label":"","tooltip":"","group":"ec3ace8.c36b93","order":2,"width":2,"height":1,"passthru":true,"mode":"text","delay":300,"topic":"","x":320,"y":340,"wires":[["ed35d989.5704a8"]]},{"id":"50d5e407.b78d34","type":"switch","z":"b44d7514.83389","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"USB","vt":"str"},{"t":"cont","v":"HDD","vt":"str"}],"checkall":"true","repair":false,"outputs":2,"x":470,"y":480,"wires":[["826e7da6.89bc"],["b1afc99b.13cf3"]]},{"id":"ed35d989.5704a8","type":"function","z":"b44d7514.83389","name":"set device","func":"flow.set(\"device\", msg.payload);\nreturn msg;","outputs":1,"noerr":0,"x":480,"y":340,"wires":[["259daa89.779ae6"]]},{"id":"44a7e2f8.c28bcc","type":"function","z":"b44d7514.83389","name":"get device","func":"var devicenow=flow.get('device');\nmsg.payload = devicenow;\nreturn msg;","outputs":1,"noerr":0,"x":310,"y":480,"wires":[["50d5e407.b78d34"]]},{"id":"9c6e90db.4c53d","type":"ui_text","z":"b44d7514.83389","group":"ec3ace8.c36b93","order":3,"width":0,"height":0,"name":"","label":"Label:","format":"{{msg.payload}}","layout":"row-left","x":1710,"y":560,"wires":[]},{"id":"72b628a5.3a4428","type":"switch","z":"b44d7514.83389","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"USB","vt":"str"},{"t":"cont","v":"HDD","vt":"str"}],"checkall":"true","repair":false,"outputs":2,"x":450,"y":680,"wires":[["692f75d5.160f24"],["6ae4a387.df2e4c"]]},{"id":"53cc1acc.29cfa4","type":"function","z":"b44d7514.83389","name":"get device","func":"var devicenow=flow.get('device');\nmsg.payload = devicenow;\nreturn msg;","outputs":1,"noerr":0,"x":310,"y":680,"wires":[["72b628a5.3a4428"]]},{"id":"2350a3d8.a3042c","type":"function","z":"b44d7514.83389","name":"get device","func":"var devicenow=flow.get('device');\nmsg.payload = devicenow;\nreturn msg;","outputs":1,"noerr":0,"x":270,"y":880,"wires":[["d140870f.57773"]]},{"id":"d140870f.57773","type":"switch","z":"b44d7514.83389","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"USB","vt":"str"},{"t":"cont","v":"HDD","vt":"str"}],"checkall":"true","repair":false,"outputs":2,"x":430,"y":880,"wires":[["611d713d.726e48","7ee0395c.eba5b"],["b72b953c.2d9cb","c1a4cd5b.269fc"]]},{"id":"b1afc99b.13cf3","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/hdd_m.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":650,"y":520,"wires":[["c7b788b2.4bcf2"],[],[]]},{"id":"c7b788b2.4bcf2","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/hdd_i.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":1010,"y":480,"wires":[["bc7259c4.a27fd"],[],[]]},{"id":"6ae4a387.df2e4c","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/hdd_unm.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":660,"y":700,"wires":[["bc7259c4.a27fd"],[],[]]},{"id":"259daa89.779ae6","type":"switch","z":"b44d7514.83389","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"USB","vt":"str"},{"t":"cont","v":"HDD","vt":"str"}],"checkall":"true","repair":false,"outputs":2,"x":630,"y":340,"wires":[["5ca805f5.1e5734"],["c7b788b2.4bcf2"]]},{"id":"b72b953c.2d9cb","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/copytohdd.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":660,"y":980,"wires":[["44ed3481.f21c14","c0eec119.31bec"],[],[]]},{"id":"c1a4cd5b.269fc","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/speedtohdd.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":670,"y":920,"wires":[["49258e25.f61e68","fdd997bc.69107"],[],[]]},{"id":"49258e25.f61e68","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/sizehdd.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":1010,"y":960,"wires":[["6b20dc3b.1afd9c"],[],[]]},{"id":"c99b943e.6fe06","type":"ui_text","z":"b44d7514.83389","group":"2fa9608d.2ce59","order":5,"width":6,"height":2,"name":"","label":"Status:","format":"{{msg.payload}}","layout":"col-center","x":1720,"y":620,"wires":[]},{"id":"c0eec119.31bec","type":"split","z":"b44d7514.83389","name":"","splt":"","spltType":"str","arraySplt":"5","arraySpltType":"len","stream":true,"addname":"","x":1550,"y":640,"wires":[["c99b943e.6fe06"]]},{"id":"d640f229.9bb7d8","type":"ui_text","z":"b44d7514.83389","group":"707b8d3f.4cca2c","order":1,"width":0,"height":0,"name":"","label":"Rpi4","format":"{{msg.payload}}","layout":"row-left","x":1030,"y":1300,"wires":[]},{"id":"35bf4d1c.c49d4a","type":"ui_button","z":"b44d7514.83389","name":"","group":"707b8d3f.4cca2c","order":2,"width":0,"height":0,"passthru":false,"label":"Refresh","tooltip":"","color":"","bgcolor":"","icon":"","payload":"reset","payloadType":"str","topic":"","x":120,"y":1360,"wires":[["b9d1c272.195b7"]]},{"id":"b9d1c272.195b7","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/info.sh","addpay":false,"append":"","useSpawn":"false","timer":"","oldrc":false,"name":"","x":640,"y":1360,"wires":[["f4498972.1504f8"],[],[]]},{"id":"c9a52cdb.f8b58","type":"ui_text","z":"b44d7514.83389","group":"707b8d3f.4cca2c","order":3,"width":0,"height":0,"name":"","label":"IP","format":"{{msg.payload}}","layout":"row-left","x":1270,"y":1360,"wires":[]},{"id":"93fdb1ad.1b7478","type":"switch","z":"b44d7514.83389","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"ip","vt":"str"},{"t":"cont","v":"mem","vt":"str"},{"t":"cont","v":"model","vt":"str"}],"checkall":"true","repair":false,"outputs":3,"x":950,"y":1380,"wires":[["b0f4b173.927a"],["9cba8fb1.0fabc8"],["3d8b8a8c.afaffe"]]},{"id":"b0f4b173.927a","type":"split","z":"b44d7514.83389","name":"","splt":"#","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1090,"y":1360,"wires":[["c9a52cdb.f8b58"]]},{"id":"b7c9eda9.1212a","type":"ui_text","z":"b44d7514.83389","group":"707b8d3f.4cca2c","order":5,"width":0,"height":0,"name":"","label":"mem:","format":" {{msg.payload}}","layout":"row-left","x":1270,"y":1400,"wires":[]},{"id":"9cba8fb1.0fabc8","type":"split","z":"b44d7514.83389","name":"","splt":"#","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1090,"y":1400,"wires":[["b7c9eda9.1212a"]]},{"id":"bf3ec8f2.346b4","type":"ui_text","z":"b44d7514.83389","group":"707b8d3f.4cca2c","order":4,"width":0,"height":0,"name":"","label":"Model","format":"{{msg.payload}}","layout":"row-left","x":1270,"y":1440,"wires":[]},{"id":"3d8b8a8c.afaffe","type":"split","z":"b44d7514.83389","name":"","splt":"#","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1090,"y":1440,"wires":[["bf3ec8f2.346b4"]]},{"id":"f4498972.1504f8","type":"split","z":"b44d7514.83389","name":"","splt":";","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":810,"y":1360,"wires":[["93fdb1ad.1b7478"]]},{"id":"d479f53b.78bff8","type":"ui_button","z":"b44d7514.83389","name":"","group":"d5572a19.225908","order":2,"width":0,"height":0,"passthru":false,"label":"PC OFF","tooltip":"","color":"","bgcolor":"","icon":"","payload":"reset","payloadType":"str","topic":"","x":120,"y":1440,"wires":[["133de056.f4e3b"]]},{"id":"133de056.f4e3b","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/turnoff.sh","addpay":false,"append":"","useSpawn":"false","timer":"","oldrc":false,"name":"","x":650,"y":1440,"wires":[[],[],[]]},{"id":"16bf75aa.55cafa","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/hdd_share.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":660,"y":1060,"wires":[["6fb97aed.b72a34"],[],[]]},{"id":"c1adcc1c.226c78","type":"ui_button","z":"b44d7514.83389","name":"","group":"78726cc2.066df4","order":1,"width":2,"height":1,"passthru":false,"label":"HDD","tooltip":"","color":"","bgcolor":"","icon":"","payload":"reset","payloadType":"str","topic":"","x":110,"y":1060,"wires":[["16bf75aa.55cafa"]]},{"id":"56f369c5.895058","type":"ui_text","z":"b44d7514.83389","group":"78726cc2.066df4","order":2,"width":4,"height":1,"name":"","label":"","format":" {{msg.payload}}","layout":"row-left","x":1130,"y":1060,"wires":[]},{"id":"6fb97aed.b72a34","type":"switch","z":"b44d7514.83389","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"status#","vt":"str"}],"checkall":"true","repair":false,"outputs":1,"x":890,"y":1060,"wires":[["2812e8f6.70483"]]},{"id":"2812e8f6.70483","type":"split","z":"b44d7514.83389","name":"","splt":"#","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1010,"y":1060,"wires":[["56f369c5.895058"]]},{"id":"9c39319d.588","type":"exec","z":"b44d7514.83389","command":"bash /home/pi/usb1_share.sh","addpay":true,"append":"","useSpawn":"true","timer":"","oldrc":false,"name":"","x":670,"y":1140,"wires":[["f663586d.fdfdd8"],[],[]]},{"id":"ad7d6b05.18546","type":"ui_button","z":"b44d7514.83389","name":"","group":"78726cc2.066df4","order":3,"width":2,"height":1,"passthru":false,"label":"USB EXT","tooltip":"","color":"","bgcolor":"","icon":"","payload":"reset","payloadType":"str","topic":"","x":120,"y":1140,"wires":[["9c39319d.588"]]},{"id":"21843513.55ab5a","type":"ui_text","z":"b44d7514.83389","group":"78726cc2.066df4","order":4,"width":4,"height":1,"name":"","label":"","format":" {{msg.payload}}","layout":"row-left","x":1150,"y":1140,"wires":[]},{"id":"f663586d.fdfdd8","type":"switch","z":"b44d7514.83389","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"status#","vt":"str"}],"checkall":"true","repair":false,"outputs":1,"x":910,"y":1140,"wires":[["35e52df5.f985da"]]},{"id":"35e52df5.f985da","type":"split","z":"b44d7514.83389","name":"","splt":"#","spltType":"str","arraySplt":1,"arraySpltType":"len","stream":false,"addname":"","x":1030,"y":1140,"wires":[["21843513.55ab5a"]]},{"id":"7f5c3aa5.c49854","type":"ui_group","z":"","name":"USB EXT","tab":"636d4846.38f48","order":1,"disp":true,"width":"6","collapse":false},{"id":"ec3ace8.c36b93","type":"ui_group","z":"","name":"COPY TO","tab":"636d4846.38f48","order":2,"disp":true,"width":"6","collapse":false},{"id":"2fa9608d.2ce59","type":"ui_group","z":"","name":"START COPY","tab":"636d4846.38f48","order":3,"disp":true,"width":"6","collapse":false},{"id":"707b8d3f.4cca2c","type":"ui_group","z":"","name":"INFO","tab":"33d11786.1c9658","order":1,"disp":true,"width":"6","collapse":false},{"id":"d5572a19.225908","type":"ui_group","z":"","name":"TURN OFF","tab":"33d11786.1c9658","order":2,"disp":true,"width":"6","collapse":false},{"id":"78726cc2.066df4","type":"ui_group","z":"","name":"SHARE","tab":"636d4846.38f48","order":4,"disp":true,"width":"6","collapse":false},{"id":"636d4846.38f48","type":"ui_tab","z":"","name":"Media Control","icon":"dashboard","order":1,"disabled":false,"hidden":false},{"id":"33d11786.1c9658","type":"ui_tab","z":"","name":"DCPD","icon":"dashboard","order":2,"disabled":false,"hidden":false}]

После добавления в Node-Red незабывайте жать Deploy

Все файлы в архиве
dcpd_files.zip

Все кирпичи описывать не буду. Тут главное скрипты которые запускает кирпич exec! Разьясню только два места

1. Это кирпич dashboar switch - он посылает дальше слова HDD или USB завсит от выбранной позиции переключателя.
2. Сразу выводит текст чтобы было понятно что сейчас выбрано
3. Это функция которая присваивает глобальной переменной device что сейчас выбрано

flow.set("device", msg.payload);
return msg;

4. Это переключатель который слушает что в потоке и напрвлят куда следует. Тут нам нужно узнать свободное место и метка диска, поэтому слушаем для кого для HDD или SSD
5. Это функуция которая берет значение глобальной переменной device и передает дальше

var devicenow=flow.get('device');
msg.payload = devicenow;
return msg;


Скрипты выпускают из себя текстовую информацию - нужную и не нужную. Тут я знаю что скрипт выпустить строку label#hdd100;asize#51515

1. Кирпич split делит строку, делитель ;
2. Выискивает нужные строки чтобы направить в нуждное место. Например label#hdd100 строку направит в сторону текстового поля label
3. Тут опять делим потому что нужно только конец строки, где именно метка, делитель #
Такой способ у меня, может есть лучше, но у меня нет!

В папку /home/pi/ создайте следующие скрипты

first_m.sh - этот скрипт монтирует первую флешку с которой будем копировать, после нажатия кнопки. И делает это не просто так а проверяет, свободно ли место куда монтировать, и неважно под какой буквой подцепилась флешка!

#!/bin/bash
if df -h | grep /mnt/usb1
then
echo "busy"
break
else
shdd=`df -h | grep /mnt/hdd | awk '{print $1}'`
for m1 in $( ls /dev/sd*[0-9]* )
do
if [ $shdd == $m1 ] 
then
echo "next"
else
sudo mount $m1 /mnt/usb1
label=`lsblk -o mountpoint,label| grep /mnt/usb1|awk '{print $2}'`
frees=`du -sm --exclude='.Trash*' /mnt/usb1| awk '{print $1}'`
echo "label#"$label";asize#"$frees
break
fi
done
fi

Из себя это скрипт выпускает строку с данным по размеру данных и метке флешки!

first_unm.sh - это скрипт просто размонтирует флешку после нажатия кнопки

#!/bin/bash
sudo umount /mnt/usb1
echo "label#no usb flash;asize#0

second_m.sh - этот скрипт монтирует вторую флешку

#!/bin/bash
hddid="289717cc-b3ec-4f12-9ae5-318b52a57a22"
hdddev=`blkid | grep $hddid | awk -F':' '{print $1}'`
echo $hdddev
if df -h | grep /mnt/usb2
then
echo "Busy"
else	
sdam=`df -h | grep usb1 | awk '{print $1}'`

echo $sdam
for m1 in $( ls /dev/sd*[0-9]* )
do
if [ $m1 != $sdam ] && [ $m1 != $hdddev ] 
then	
sudo mount $m1 /mnt/usb2
echo "ok"
break
fi
done
fi

тут важно заполнить UUID для своего HDD, выше было показано как его искать!

second_i.sh - за ним идет скрипт который дает информацию о доступном месте и метке флешки

#!/bin/bash
m1=`df -h | grep /mnt/usb2|awk '{print $1}'`
label=`lsblk -o mountpoint,label| grep /mnt/usb2|awk '{print $2}'`
frees=`df -m|grep $m1 | awk '{print $4}'`
echo "label#"$label";asize#"$frees

Скрипт обновляет информацию при монтирование, и при переключения переключателя Change device

second_unm.sh - этот скрипт просто размонтирует флешку после нажатия кнопки

#!/bin/bash
sudo umount /mnt/usb2
echo "label#no usb flash;asize#0"

Хорошо что для размонтирования нужно знать только имя папки, а не устройства

Соотвественно такие же скипты спецаильно для HDD
hdd_m.sh

#!/bin/bash
hddid="289717cc-b3ec-4f12-9ae5-318b52a57a22"
if df -h | grep /mnt/hdd/
then
echo "busy"
break
else
sudo mount -U $hddid /mnt/hdd 
echo "ok"
fi

Здесь тоже свой уникальный UUID

hdd_i.sh

#!/bin/bash
m1=`df -h | grep /mnt/hdd|awk '{print $1}'`
label=`lsblk -o mountpoint,label| grep /mnt/hdd|awk '{print $2}'`
frees=`df -m|grep $m1 | awk '{print $4}'`
echo "label#"$label";asize#"$frees

hdd_unm.sh

#!/bin/bash
sudo umount /mnt/hdd/
echo "label#no hdd;asize#0

Далее идут кирпичи отвечающие за копирование
copytohdd.sh - по нажатии кнопки, смотрит есть ли флешки c которйо копироваь, смотрит есть ли hdd, и начинает копировать в новую папку с именем даты начала копирования.

#!/bin/bash
if df -h | grep /mnt/usb1
then
if df -h | grep /mnt/hdd
then
pathnew=`date +"%Y%m%d%H%M%S"`
echo "pathonusb#"$pathnew
sudo mkdir /mnt/hdd/$pathnew
sudo rsync -av  --exclude=".\Tra*" /mnt/usb1/* /mnt/hdd/$pathnew
fi
fi

speedtohdd.sh - чудесный скрипт, рисует прогресс копирования. Следит за изменением размера занятого места на флешке, знает размер данных которые надо скопировать. Но все раво это только для визуализации

#!/bin/bash
fsize=`du -s --exclude='.Trash*' /mnt/usb1| awk '{print $1}'`
frees=`df -k | grep /mnt/hdd | awk '{print $3}'`
fres=0
ndelay=0
echo $fres
while [ $fres -lt 100 ]; do
fresold=$fres
frees2=`df -k | grep /mnt/hdd | awk '{print $3}'`
fres=`echo "(100*($frees2-$frees))/$fsize" | bc`
if [ $fres -gt 100 ]
then
fres=100
fi
if [ $fres -eq $fresold ]
then
let ndelay++
if [ $ndelay -gt 500 ]
then	
fres=100
fi
else
ndelay=0	
fi
echo $fres
done

И скрипт sizehdd.sh который обновляет совобдное место на второй флешке, запускает вместе с sdaspeed.sh

#!/bin/bash
m1=`df -h | grep /mnt/hdd|awk '{print $1}'`
frees=`df -m|grep $m1 | awk '{print $4}'`
echo "asize#"$frees

Соотвественно такие же скипты специaльно для копирования на USB
copytousb.sh

#!/bin/bash
if df -h | grep /mnt/usb1
then
if df -h | grep /mnt/usb2
then
pathnew=`date +"%Y%m%d%H%M%S"`
echo "pathonusb#"$pathnew
sudo mkdir /mnt/usb2/$pathnew
#sudo cp -rf /mnt/usb1/*  /mnt/usb2/$pathnew
sudo rsync -av  --exclude=".\Tra*" /mnt/usb1/* /mnt/usb2/$pathnew
fi
fi

speedtousb.sh

#!/bin/bash
fsize=`du -s --exclude='.Trash*' /mnt/usb1| awk '{print $1}'`
frees=`df -k | grep /mnt/usb2 | awk '{print $3}'`
fres=0
ndelay=0
echo $fres
while [ $fres -lt 100 ]; do
fresold=$fres
frees2=`df -k | grep /mnt/usb2 | awk '{print $3}'`
fres=`echo "(100*($frees2-$frees))/$fsize" | bc`
if [ $fres -gt 100 ]
then
fres=100
fi
if [ $fres -eq $fresold ]
then
let ndelay++
if [ $ndelay -gt 500 ]
then	
fres=100
fi
else
ndelay=0	
fi
echo $fres
done

sizeusb2.sh

#!/bin/bash
m1=`df -h | grep /mnt/usb2|awk '{print $1}'`
frees=`df -m|grep $m1 | awk '{print $4}'`
echo "asize#"$frees

Теперь скрипты чтобы поделится на сайте - они совсем простые, просто добавляют или убирают если уже есть, символическую ссылку в папку сайта!
usb1_share.sh

#!/bin/bash
if df -h | grep /mnt/usb1
then
if ls /var/www/html/data/usbext 
then
sudo rm /var/www/html/data/usbext
echo "status#Not shared"
else
echo "status#Shared"
sudo ln -s /mnt/usb1 /var/www/html/data/usbext
echo "status#Shared"
fi
else
sudo rm /var/www/html/data/usbext
echo "status#Not mounted"
fi

hdd_share.sh

#!/bin/bash
if df -h | grep /mnt/hdd
then
if ls /var/www/html/data/hdd 
then
sudo rm /var/www/html/data/hdd
echo "status#Not shared"
else
echo "status#Wait"
sudo ln -s /mnt/hdd /var/www/html/data/hdd
echo "status#Shared"
fi
else
sudo rm /var/www/html/data/hdd
echo "status#Not mounted"
fi

Скрипт для чтения температур Raspberry rpitemp.sh

#!/bin/bash
vcgencmd measure_temp

Скрипт для вывод информации о малинке
info.sh

#!/bin/bash
model=`cat /sys/firmware/devicetree/base/model`
mem=`free -ht | grep Total| awk '{print $2}'`
ip=`hostname -I`
echo "ip#"$ip";model#"$model";mem#"$mem

И скрипт выключения, он просто запускает команду и надо смотреть глазами когда зеленая лампочка перестанет мигать, тогда можно и кнопку нажимать на корпусе до упора!
info.sh

#!/bin/bash
sudo shutdown -h now

Закрываем доступ к администрированию Node-Red и управлению DCPD
Ставим
npm install bcryptjs
Идем в
cd /home/pi/.node-red
Генерируем краказябру своего пароля коммандой
node -e "console.log(require('bcryptjs').hashSync(process.argv[1], 8));" your-password-here
у меня будет один пароль и для админ панели и для панели DCPD!
В файле settings.js
vi /home/pi/.node-red/settings.js
находим строки и расскомментируем должно быть вот так, со своей краказяброй вместо пароля

adminAuth: {
    sessionExpiryTime: 86400,
    type: "credentials",
    users: [{
        username: "admin",
        password: "$2a$08$ToLl/u9QXxbIWcP2Xjsul.fTgujmnDjVLAgyOwpxNtIRU7TWr.XBu",
        permissions: "*"
    }]
},

httpNodeAuth: {
user:"user",
pass:"$2a$08$ToLl/u9QXxbIWcP2Xjsul.fTgujmnDjVLAgyOwpxNtIRU7TWr.XBu"
},

Перезапускаем node-Red
sudo service nodered restart

Подключаемся к Wi-Fi DCPD, заходим под своим паролем, в панель DCPD по адресу http://10.100.10.1:1880/ui и делаем что-то!

Подключаем флешку, дальше как на видео!


Добавить комментарий

Ваш адрес email не будет опубликован.