home /
infca /
rspi3
(navigation links)
|
Que és lo mes divertit que t'ha passat avui ?
Gracies, JA ! |
Raspall -
instalació +
configuració
|
tcpdump,
bluetooth
|
GPIO ,
PWM ,
I2C ,
SPI
|
Software &
putty
|
Semàfor,
hw,
sw,
cfg & UG
|
*** new router ***
SAG :
r3 startup,
R3 TCPIP cfg,
versions sw,
cron R3,
projectes
|
LED
|
calcul SSR i LED
canvi SD, backup,
2 TB SD,
R3 new SD Nov 2024,
Desembre 2024
sound
|
remote control
&
picture
|
pin de entrada
|
Alexa
|
sensor soroll per Roda
Lo Pere
|
ESP,
backup,
deures
|
MTV -
deures ,
xarxa ,
engega R4 ,
servei de usuari ;
ventilador
R4 SAG -
r4 statup,
r4 crontab
|
/boot/config.txt
|
R4 new SD 2022 +
scripts +
soft,
R4 TCPIP cfg,
bot as service,
webcam
restart GUI, X11
|
hw misc, as semafor
|
Alby
|
wifi JALL
|
enviar Email
|
enviar WhatsApp
|
obrir ports
|
Pi0
|
pi.4
all soft & shells at all Rx,
webmin
|
all cron shells
boot USB
|
recovery mode
|
troubleshooting +
serial port logging
|
Links
|
End
|
mapa
|
Jocs amb la Raspberry Pi 3 model B, des l'estiu 2016
go 2 top
Specs
El Raspberry Pi ...
- has ARM architecture
- conté Linux Debian, Fedora, Openwrt i 30 sistemes mes - te tot el que et puguis imaginar i mes :-)
Some webs :
Mine has :
- System-on-chip : Broadcom BCM2837
- CPU - 1,2 GHz 64-bit Quad-core ARM Cortex-A53
- GPU: Broadcom VideoCore IV
- graphics - Broadcom VideoCore IV 300 MHz
- RAM - 1 GB LPDDR2 at 900MHz
- storage - MicroSDHC slot
- HDMI amb 1920 x 1080 x 60p
- networking
- 1x RJ45 amb 10/100 Ethernet
- 2,4 GHz 802.11n wireless - CYW43438 xip
- bluetooth: Bluetooth 4.1 Classic, Bluetooth Low Energy
- 4x USB 2.0
- power - 800 mA (4.0 W)
CPU 32/64
The earlier models of Raspberry Pi 2 use a Broadcom BCM2836 SoC with a 900 MHz 32-bit quad-core ARM Cortex-A7 processor, with 256 KB shared L2 cache.
The Raspberry Pi 3 uses a Broadcom BCM2837 SoC with a 1.2 GHz 64-bit quad-core ARM Cortex-A53 processor, with 512 KB shared L2 cache.
ARMv7 and below are 32-bit. AMRv8 introduces the 64-bit instruction set.
Here's the Cortex-A53 doc
Rasp and Linux kernel and NOOBS at github
display 32/64
If you're running Raspbian then it'll be 32 bit.
Run "uname -m" or "uname -a" to confirm.
If it says aarch64 then it is 64 bit. If it says armv7l then it is 32 bit.
pi@pi0:~ $ uname -a
Linux pi0 5.10.103+ #1529 Tue Mar 8 12:19:18 GMT 2022 armv6l GNU/Linux
pi@r3-64gb:~ $ uname -a
Linux r3-64gb 6.6.51+rpt-rpi-v7 #1 SMP Raspbian 1:6.6.51-1+rpt3 (2024-10-08) armv7l GNU/Linux
pi@R4:~ $ uname -a
Linux R4 5.10.103-v7l+ #1529 SMP Tue Mar 8 12:24:00 GMT 2022 armv7l GNU/Linux *** sorpresa ***
Interesting command : Lots of commands [***]
pi@R4:~ $ getconf LONG_BIT
32
HDMI on TV
**Raspberry Pi 4 Model B:** display must be connected to HDMI port closest to power jack.
The cable shows up as "v 60 Hz, 1920 x 1080 i"
See
restart GUI
On-board LEDs
- Red PWR LED
- on if power OK
- flashes (or goes out) if the power drops below about 4.63V
- Green ACT LED
- steady on if no SD card during boot
- irregular flashes for SD card access
- Ethernet Socket Left LED (yellow)
- on 100-Mbps connection
- off 10-Mbps connection
- Ethernet Socket Right LED (green)
- on if link established
- flashes for port activity
- off if no link is established
url
RPI access to internal devices
gpiozero
We can use gpio +
internal devices : asCPUTemperature
vcgencmd
RPI "vcgencmd commands"
sag@odin:~ $ vcgencmd commands
commands="vcos, ap_output_control, ap_output_post_processing, vchi_test_init, vchi_test_exit,
vctest_memmap, vctest_start, vctest_stop, vctest_set, vctest_get,
pm_set_policy, pm_get_status, pm_show_stats, pm_start_logging, pm_stop_logging,
version, commands, set_vll_dir, set_backlight, set_logging, get_lcd_info, arbiter, cache_flush, otp_dump, test_result, codec_enabled,
get_camera, get_mem, measure_clock, measure_volts, scaling_kernel, scaling_sharpness, get_hvs_asserts, get_throttled, measure_temp,
get_config, hdmi_ntsc_freqs, hdmi_adjust_clock, hdmi_status_show, hvs_update_fields, pwm_speedup, force_audio,
hdmi_stream_channels, hdmi_channel_map,
display_power, read_ring_osc, memtest, dispmanx_list, get_rsts, schmoo, render_bar, disk_notify, inuse_notify,
sus_suspend, sus_status, sus_is_enabled, sus_stop_test_thread, egl_platform_switch, mem_validate, mem_oom, mem_reloc_stats,
hdmi_cvt, hdmi_timings, file"
Comparem Raspberry Pi 3 model "B" amb Raspberry Pi 3 model "B+"
Specs | model B+ (2018) | model B (2016)
|
CPU
| Broadcom BCM2837B0, Cortex-A53 (ARMv8) 64-bit SoC @ 1.4 GHz
| Broadcom BCM2837, Cortex-A53 (ARMv8) 64-bit SoC @ 1.2 GHz
|
RAM
| 1GB RAM
| 1GB RAM
|
Connectivity
| WiFI 802.11.b/g/n/ac, 2.4GHz and 5GHz, Bluetooth 4.2, Ethernet 300Mbps
| WiFi 802.11 b/g/n (2.4GHz), Bluetooth 4.1, Ethernet 100Mbps
|
Ports
| HDMI, 4 USB 2.0, Micro SD, CSI camera, DSI display
| HDMI, 4 USB 2.0, Micro SD, CSI camera, DSI display
|
Few commands to see the difference :
- lsusb
- lscpu
- procinfo
- hciconfig
- lshw
sag@odin:~ $ lsusb
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub {1 hub controller -> model "B"}
sag@odin:~ $ lscpu
Architecture: armv7l
Byte Order: Little Endian
CPU(s): 4
On-line CPU(s) list: 0-3
Thread(s) per core: 1
Core(s) per socket: 4
Socket(s): 1
Model name: ARMv7 Processor rev 4 (v7l)
CPU max MHz: 1200.0000 {1200 -> model "B", model "B+" is 1.400}
CPU min MHz: 600.0000
sag@odin:~ $ cat /proc/cpuinfo
model name : ARMv7 Processor rev 4 (v7l)
BogoMIPS : 38.40
Hardware : BCM2835
Revision : a02082 {a02082 -> model "B"}
Serial : 00000000e8479254
sebas@henry:/proc $ hciconfig -a
hci0: Type: Primary Bus: UART
BD Address: B8:27:EB:05:FF:F4 ACL MTU: 1021:8 SCO MTU: 64:1
UP RUNNING
Name: 'henry'
Class: 0x480000
HCI Version: 4.1 (0x7) Revision: 0x168 {4.1 is model "B", model "B+" is 4.2}
LMP Version: 4.1 (0x7) Subversion: 0x2209
Manufacturer: Broadcom Corporation (15)
Few links :
lets use NOOBS
Beginners should start with NOOBS ,
or New Out Of the Box Software to give it its full name.
NOOBS requirements
NOOBS_v3_2_0.zip is 2,3 GB and NOOBS v3_1_1.zip is 1,5 GB
- SD card :
- for installation of Raspberry Pi OS with desktop and recommended software (Full) via NOOBS the minimum card size is 16 GB
- for the image installation of Raspberry Pi OS with desktop and recommended software, the minimum card size is 8 GB
- for Raspberry Pi OS Lite image installations we recommend a minimum of 4 GB
- some distributions, for example LibreELEC and Arch, can run on much smaller cards
NOOBS setup
- download NOOBS
into W500 {c:\temp\rsp3\NOOBS_v3_2.zip} - see "gDrive(gruta)"
- unzip the file into "C:\temp\rsp3\NOOBS_v3_2"
- connect the SD card to W500 using square USB adapter {not flat}
- set up your SD card :
- clear the SD : C:\> format /fs:fat32 f: - Raspberry Pi can only read FAT32 volumes
- format the SD card as FAT32 using
gui_FAT32_format {\\w500\eines}
Allocation Unit Size = 32768 ;
if you want to use NOOBS on a card that is 64 GB or larger,
you need to reformat it as FAT32 first before copying the NOOBS files to it
url
- see SD formatter for cards under 32 GB
- copy the NOOBS files {contents of "C:\temp\rsp3\NOOBS_v3_2"} onto the SD card :
- 3 directoris (v 3.1.2) : "defaults", "os" and "overlays"
- 22 files, as "bcm2708-rpi-b.dtb" and "riscos-boot.bin"
- if you have a 2 GB SD card, you have to use Noobs v 3.1.1, as 3.1.2 requires 250 MB more of space !
url
2 GB SD card - SSD disk
The PiZero does not like 64 GB SD, so I used a 2 GB.
Then, the OS does not have space for its data, so I connect a SSD disc.
pi@raspberrypi:~ $ cat /boot/cmdline-original.txt
dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=/PARTUUID=01bff0c0-02 rootfstype=ext4
pi@raspberrypi:~ $ cat /boot/cmdline-ssd.txt
dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=/dev/sda rootfstype=ext4 elevator= ?
lash plymouth.ignore-serial-consoles
- conecta SSD
- bota raspbian
- sudo parted /dev/sda
- fer 1 sola particio que ocupi tot el disc
- comanda : ?
- fer rsync
Instal.lació
Compra
El kit de Diotronic (87,45 €) inclou
- black case - 5 €
- Raspberry Pi 3 model B - 37,50 €
- power supply 2,5 A - 11 €
- 2m UTP
- 1m HDMI
- 16GB microSD class10 with NOOBS v 1.8 pre-installed -
7 €
Engegada inicial
- insert SD card into slot
- connect USB keyboard and mouse
- connect HDMI into monitor
- connect Ethernet cable to router (or use wifi)
- plugin power supply to boot Raspberry Pi
Configuració del "raspall"
- NOOBS instala Debian / Raspbian
- hostname := "raspall" ;
- default user = "pi", default password = "raspberry" ;
- passwd pi : u = "pi", p = "bcn10" ; u2 = "sag", p2 = "<ya_3>2016" ;
- setup wireless
for IP := 192.168.1.123 (instead of DHCP) - see bellow
El sistema operatiu es Raspbian,
a portmanteau of Raspberry and Debian.
sebas@henry:~ $ uname -a
Linux henry 4.14.79-v7+ #1159 SMP Sun Nov 4 17:50:20 GMT 2018 armv7l GNU/Linux
pi@R4:~ $ cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 10 (buster)"
pi@R4:~ $ hostnamectl
Static hostname: R4
Icon name: computer
Machine ID: 8b60fee1041c44139eeeacbb081d0c2e
Boot ID: 88ed1d4c48b84d2a963eb1b67c2b23a4
Operating System: Raspbian GNU/Linux 10 (buster)
Kernel: Linux 5.10.103-v7l+
Architecture: arm
Lots of commands [***]
raspi-config command
La configuracio mes interna del Raspberry es fa amb la comanda "raspi-config"
Llegir raspi-config.init
Per exemple, permet posar una clau de pas curta
raspi-config : wifi setup
- start raspi-config with: sudo raspi-config
- go into System Options > Wireless LAN
- type your SSID and your password
- exit the tool - after a few seconds, your Pi is now connected to the wireless network you chose
raspberry tips
Filesystem
El nostre filesystem és:
pi@raspberrypi-llovet:~ $ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/root 14G 3.6G 9.1G 28% /
devtmpfs 459M 0 459M 0% /dev
tmpfs 463M 0 463M 0% /dev/shm
tmpfs 463M 6.4M 457M 2% /run
tmpfs 5.0M 4.0K 5.0M 1% /run/lock
tmpfs 463M 0 463M 0% /sys/fs/cgroup
/dev/mmcblk0p6 63M 20M 44M 31% /boot
tmpfs 93M 0 93M 0% /run/user/1000
/dev/mmcblk0p5 30M 417K 28M 2% /media/pi/SETTINGS
pi@raspberrypi-llovet:~ $
Raspbian repository
Homepage :
The Raspbian repository is the entire set of Raspbian packages
organized in a special on-line directory tree
which can be used to install thousands of additional software packages on your Raspberry Pi.
The /etc/apt/sources.list file contains the information
needed to install additional software packages on your Raspberry Pi from the Raspbian repository.
This file should contain the following information:
deb http://archive.raspbian.org/raspbian wheezy main contrib non-free
deb-src http://archive.raspbian.org/raspbian wheezy main contrib non-free
If needed, the Raspbian public key can be stored into your apt-get keyring using the following command:
wget https://archive.raspbian.org/raspbian.public.key -O - | sudo apt-key add -
You can browse the package list
here or
here, in "software" section
To search the local package repository index, use:
$ apt-cache search <keyword>
TCP/IP
Basic values :
pi@raspberrypi-llovet:~ $ ifconfig
eth0 Link encap:Ethernet HWaddr b8:27:eb:ab:6b:bc
inet6 addr: fe80::90a5:8293:2880:8eca/64 Scope:Link
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:456 errors:0 dropped:0 overruns:0 frame:0
TX packets:456 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:37392 (36.5 KiB) TX bytes:37392 (36.5 KiB)
wlan0 Link encap:Ethernet HWaddr b8:27:eb:fe:3e:e9
inet addr:192.168.1.45 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::ba27:ebff:fefe:3ee9/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:2715 errors:0 dropped:1479 overruns:0 frame:0
TX packets:828 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:620516 (605.9 KiB) TX bytes:141177 (137.8 KiB)
Show wireless configuration
pi@raspberrypi-llovet:~ $
iw list - manipulate wireless devices
Some details :
pi@raspberrypi-llovet:~ $ iwlist wlan0 scan
wlan0 Scan completed :
Cell 01 - Address: E0:41:36:BC:BC:D2
Channel:1
Frequency:2.412 GHz (Channel 1)
Quality=28/70 Signal level=-82 dBm
Encryption key:on
ESSID:"enxaneta"
Show what interfaces will be brought up (from /etc/network/interfaces I'd say) :
ifquery --list --allow=hotplug
Wifi values (usr/pwd) are stored in file /etc/wpa_supplicant/wpa_supplicant.conf.
IP values (static IP, default gateway, DNS's) are in /etc/dhcpcd.conf, also displayed at /etc/resolv.conf
Sample :
pi@odin:/etc/wpa_supplicant $ sudo cat wpa_supplicant.conf
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB ; raspall "DE", odin "ES"
network={
ssid="enxaneta"
psk="my-enxaneta-pwd"
key_mgmt=WPA-PSK
}
Display available wifi's at 2,4 GHz:
pi@odin:~ $ sudo iwlist wlan0 scan | grep ESSID
ESSID:"WLAN_GAS2"
ESSID:"enxaneta"
ETH0 with static IP
Get interface :
pi@raspberrypi-llovet:~ $ cat /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8)
# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and "man dhcpcd.conf"
# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d
auto lo
iface lo inet loopback
iface eth0 inet manual
allow-hotplug wlan0
iface wlan0 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
allow-hotplug wlan1
iface wlan1 inet manual
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
The line iface eth0 inet dhcp means we get an IP using DHCP.
Get some details :
pi@raspberrypi-llovet:~ $ netstat -nr
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 192.168.1.1 0.0.0.0 UG 0 0 0 wlan0
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 wlan0
pi@raspberrypi-llovet:~ $ route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.1.1 0.0.0.0 UG 303 0 0 wlan0
192.168.1.0 0.0.0.0 255.255.255.0 U 303 0 0 wlan0
Write down gateway (192.168.1.1) and net mask (255.255.255.0)
Set values in /etc/network/interfaces file, as
auto eth0
iface eth0 inet static ; do not use DHCP
address 192.168.1.118 ; select value with care
gateway 192.168.1.1 ; way to external world
netmask 255.255.255.0 ; or /24
network 192.168.1.0 ;
broadcast 192.168.1.255 ;
Restart network
pi@raspberry: sudo /etc/init.d/networking restart
pi@raspberry: sudo /etc/init.d/networking reload
pi@raspberry: sudo reboot
elinux
Wireless with static IP
Read doc
To set a fixed IP, edit /etc/dhcpcd.conf to include
interface wlan0
static ip_address=192.168.1.123/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 8.8.4.4
stackexchange,
archlinux
Get (generated) DNS :
pi@raspberrypi-llovet:~ $ cat /etc/resolv.conf
# Generated by resolvconf
domain telefonica.net
nameserver 80.58.61.250
nameserver 80.58.61.254
A can Llovet (wifi card "Intel(R) WiFi Link 5100 AGN") hem de posar :
ip = 192.168.1.123
dgw = 192.168.1.1
dns = 80.58.61.250 80.58.61.254
wifi id
How to know what wifi are we connected to ?
pi@odin:/etc $ iwgetid
wlan0 ESSID:"enxaneta"
pi@odin:/etc $ iwconfig
wlan0 IEEE 802.11bgn ESSID:"enxaneta"
Mode:Managed Frequency:2.412 GHz Access Point: E0:41:36:BC:BC:D2
Bit Rate=14.4 Mb/s Tx-Power=31 dBm
Retry short limit:7 RTS thr:off Fragment thr:off
Power Management:on
Link Quality=37/70 Signal level=-73 dBm
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:119 Invalid misc:0 Missed beacon:0
To display available wifi's, use
pi@odin:/etc $ sudo iwlist wlan0 scan
Intermitent disconnect
Can be due to power management. Disable it using the command
sudo iwconfig wlan0 power off
To keep power management off after reboot, add to
/etc/rc.local :
/bin/sleep 30 ; wait for the association of the wlan0 connection {? trenca rc.local ? path absolut ?}
/sbin/iwconfig wlan0 power off
Verify it is disabled :
pi@odin:~/logs $ iwconfig wlan0
wlan0 IEEE 802.11bgn ESSID:"enxaneta"
Mode:Managed Frequency:2.412 GHz Access Point: E0:41:36:BC:BC:D2
Bit Rate=5.5 Mb/s Tx-Power=31 dBm
Retry short limit:7 RTS thr:off Fragment thr:off
Power Management:off
Link Quality=35/70 Signal level=-75 dBm
Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0
Tx excessive retries:12 Invalid misc:0 Missed beacon:0
Get IP's (internal/external) into shell
#!/bin/bash
ipexterna=$(curl -m 2 -s icanhazip.com);
ipexterna=$(curl -m 2 -s http://checkip.amazonaws.com)
rc1=$?
echo ">>> (2) icanhazip rc ($rc1)"
myip="$(/sbin/ifconfig wlan0 | grep 'inet addr:192' | cut -d: -f2 | awk '{ print $1}')"
szIP="Today IPs : external {$ipexterna}, internal {$myip}."
Restart wifi
Try
pi@odin:~/eines $ cat wifi_restart.sh
#!/bin/bash
# https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=25854
TESTIP=8.8.8.8
ping -c2 ${TESTIP} > /dev/null
if [ $? != 0 ]
then
ifdown --force wlan0
ifup wlan0
service ssh restart
service xrdp restart
fi
Another :
#!/bin/bash
NetCard=wlan0 # the netcard connected to the internet
PingTarget=www.baidu.com # the ping target, router ip or website, etc: 192.168.1.1, www.baidu.com
LogFile=~/NetReconnector.log # log file
LogAll=false # log msg no matter whether the net is connected = check whether the script is running
test -e $LogFile || touch $LogFile
time=$(date "+%Y/%m/%d %H:%M:%S")
ret=$(ping -c 2 -W 1 -I $NetCard $PingTarget | grep 'received' | cut -d ',' -f 2 | cut -d ' ' -f 2)
if [ "$ret" == "0" ]; then
sudo ifdown wlan0 && sudo ifup wlan0
echo "Try Reconnect: $?, $time" | tee -a $LogFile
else
if [ "$LogAll" == "true" ]; then
echo "Network is ok, ret = $ret, $time" | tee -a $LogFile
fi
fi
exit 0
url
headless wifi
pi 3 B+ headless SSH access over wifi
Another url
Sequence is :
- write a Raspbian image onto the SD card
- open the SD card on Ubuntu to see the small FAT32 partition
- create a "ssh.txt" file with any contents
- create a "wpa_supplicant.conf" file containing :
#!/bin/bash
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=US
network={
ssid="Your network SSID"
psk="Your WPA/WPA2 security key"
key_mgmt=WPA-PSK
}
Set proper values for "country", "ssid" and "psk"
My machines :
pi@R4:/etc/wpa_supplicant $ cat wpa_supplicant.conf
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB
network={
ssid="la.meva.xarxa"
psk="la.meva.clau"
key_mgmt=WPA-PSK
}
Una altra :
pi@pi0:/etc/wpa_supplicant $ cat wpa_supplicant.conf
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=ES
network={
ssid="la.meva.xarxa"
psk="la.meva.clau"
}
Curiosament el R3 no te eixe fitxer ... en ser ""
Solucio : use nmcli, command-line tool for controlling NetworkManager
sudo nmcli radio wifi on
sudo nmcli dev wifi connect <wifi-ssid> password "<network-password>"
Dougie Lawson
Tenim les dades en aquest fitxer :
pi@r3-64gb:/etc/NetworkManager/system-connections $ sudo cat preconfigured.nmconnection
[connection]
id=preconfigured
uuid=7d5ad85d-2b82-422d-b776-289e054fd7d8
type=wifi
timestamp=1733837337
[wifi]
mode=infrastructure
ssid=MyWifiName
[wifi-security]
key-mgmt=wpa-psk
psk=e32b314d5b8caafc5e0e502810bc16664943a5aae30f2e0e9f566ef3a063c3bc
[ipv4]
address1=192.168.1.123/24,192.168.1.1
dns=8.8.8.8;
method=manual
[ipv6]
addr-gen-mode=default
method=auto
[proxy]
La comanda magica es ... nmtui - text user interface for controlling NetworkManager (curse-based APP)
nmcli versus nmtui
- nmcli is more flexible and powerful
- nmtui is easier to use and more user-friendly
infotechys
tcpdump
$ sudo apt update -- update the repository index
$ sudo apt-cache search tcpdump -- search packages :
linuxhint
$ sudo apt-get install tcpdump -- install
$ sudo tcpdump -- display packets (dont use from ssh !)
$ sudo tcpdump -w test.pcap -c 1000 -- write to file, ready for wireshark
url
Bluetooth
sag@odin:~ $ sudo bluetoothctl
[sudo] password for sag:
[NEW] Controller B8:27:EB:ED:38:FE odin [default]
[bluetooth]# agent on
Agent registered
[bluetooth]# default-agent
Default agent request successful
[bluetooth]# scan on
Discovery started
[CHG] Controller B8:27:EB:ED:38:FE Discovering: yes
[NEW] Device 42:B5:7B:9F:1A:0F 42-B5-7B-9F-1A-0F
[bluetooth]# pair 42:B5:7B:9F:1A:0F
Attempting to pair with 42:B5:7B:9F:1A:0F
[CHG] Device 42:B5:7B:9F:1A:0F Connected: yes
[CHG] Device 42:B5:7B:9F:1A:0F UUIDs:
00001800-0000-1000-8000-00805f9b34fb
00001801-0000-1000-8000-00805f9b34fb
00001805-0000-1000-8000-00805f9b34fb
0000180a-0000-1000-8000-00805f9b34fb
0000180f-0000-1000-8000-00805f9b34fb
7905f431-b5ce-4e99-a40f-4b1e122d00d0
89d3502b-0f36-433a-8ef4-c502ad55f8dc
9fa480e0-4967-4542-9390-d343dc5d04ae
d0611e78-bbb4-4591-a5f8-487910ae4366
[CHG] Device 42:B5:7B:9F:1A:0F Paired: yes
Pairing successful
[CHG] Device 42:B5:7B:9F:1A:0F Appearance: 0x0280
[CHG] Device 42:B5:7B:9F:1A:0F Icon: multimedia-player
[CHG] Device 42:B5:7B:9F:1A:0F RSSI: -75
[CHG] Device 42:B5:7B:9F:1A:0F Trusted: yes
[CHG] Device 42:B5:7B:9F:1A:0F RSSI: -83
[CHG] Device 42:B5:7B:9F:1A:0F RSSI: -92
[NEW] Device 49:0F:A0:1A:9D:0F 49-0F-A0-1A-9D-0F
[CHG] Device 42:B5:7B:9F:1A:0F RSSI: -71
[CHG] Device 42:B5:7B:9F:1A:0F RSSI: -85
[NEW] Device FC:58:FA:D6:A6:3B LG FJ0(3B)
[CHG] Device 42:B5:7B:9F:1A:0F RSSI: -75
[CHG] Device 42:B5:7B:9F:1A:0F RSSI: -83
[bluetooth]# help
Available commands:
list List available controllers
show [ctrl] Controller information
select <ctrl> Select default controller
devices List available devices
paired-devices List paired devices
power <on/off> Set controller power
pairable <on/off> Set controller pairable mode
discoverable <on/off> Set controller discoverable mode
agent <on/off/capability> Enable/disable agent with given capability
default-agent Set agent as the default one
scan <on/off> Scan for devices
info <dev> Device information
pair <dev> Pair with device
trust <dev> Trust device
untrust <dev> Untrust device
block <dev> Block device
unblock <dev> Unblock device
remove <dev> Remove device
connect <dev> Connect device
disconnect <dev> Disconnect device
version Display version
quit Quit program
[bluetooth]#
url
USB scan
lsusb -v
USB webcams
Logitech vermella
En conectar-la, veiem a /var/log/dmesg :
[11322.203263] usb 1-1.3: new full-speed USB device number 6 using dwc_otg
[11322.310155] usb 1-1.3: New USB device found, idVendor=046d, idProduct=08da
[11322.310177] usb 1-1.3: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[11322.352338] media: Linux media interface: v0.10
[11322.377214] Linux video capture interface: v2.00
[11322.387384] gspca_main: v2.14.0 registered
[11322.394686] gspca_main: gspca_zc3xx-2.14.0 probing 046d:08da
[11323.555427] input: gspca_zc3xx as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.3/input/input3
[11323.561256] usbcore: registered new interface driver gspca_zc3xx
[11323.615681] usbcore: registered new interface driver snd-usb-audio
USB devices list - see vendor ID (VID) and product ID (PID) :
pi@odin:~/semafor $ lsusb
Bus 001 Device 005: ID 04f3:0210 Elan Microelectronics Corp. Optical Mouse
Bus 001 Device 004: ID 17ef:6047 Lenovo
Bus 001 Device 006: ID 046d:08da Logitech, Inc. QuickCam Messanger
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Modules :
pi@odin:~/semafor $ lsmod
Module Size Used by
snd_usb_audio 118608 0
snd_hwdep 5727 1 snd_usb_audio
snd_usbmidi_lib 19801 1 snd_usb_audio
snd_rawmidi 18452 1 snd_usbmidi_lib
snd_seq_device 3621 1 snd_rawmidi
gspca_zc3xx 39480 0
gspca_main 22823 1 gspca_zc3xx
v4l2_common 3929 1 gspca_main
videodev 132913 3 gspca_main,v4l2_common,gspca_zc3xx
media 11573 1 videodev
bnep 10340 2
hci_uart 17943 1
btbcm 5929 1 hci_uart
bluetooth 326105 22 bnep,btbcm,hci_uart
brcmfmac 186599 0
brcmutil 5661 1 brcmfmac
snd_bcm2835 20511 1
cfg80211 427855 1 brcmfmac
snd_pcm 75698 2 snd_bcm2835,snd_usb_audio
rfkill 16037 4 cfg80211,bluetooth
snd_timer 19160 1 snd_pcm
snd 51844 10 snd_bcm2835,snd_usb_audio,snd_hwdep,snd_timer,snd_pcm,snd_rawmidi,snd_usbmidi_lib,snd_seq_device
bcm2835_gpiomem 3040 0
bcm2835_wdt 3225 0
evdev 11396 8
joydev 9024 0
uio_pdrv_genirq 3164 0
uio 8000 1 uio_pdrv_genirq
i2c_dev 5859 0
fuse 83461 3
ipv6 347530 48
Module GSPCA :
pi@odin:~/semafor $ lsmod | grep gspca
gspca_zc3xx 39480 0
gspca_main 22823 1 gspca_zc3xx
v4l2_common 3929 1 gspca_main
videodev 132913 3 gspca_main,v4l2_common,gspca_zc3xx
Drivers :
pi@odin:~ $ v4l2-ctl --list-formats - list all the video modes supported by camera
ioctl: VIDIOC_ENUM_FMT
Index : 0
Type : Video Capture
Pixel Format: 'JPEG' (compressed)
Name : JFIF JPEG
Dona un error extrany en funcionar una estona llarga :
pi@odin:~ $ dmesg
[177197.374854] gspca_zc3xx 1-1.2:1.0: URB error -32, resubmitting
[177197.382888] gspca_zc3xx 1-1.2:1.0: URB error -32, resubmitting
[177197.383112] usb 1-1.2: USB disconnect, device number 7
Logitech blava
En conectar-la, veiem a /var/log/dmesg :
[177624.937723] usb 1-1.2: new full-speed USB device number 8 using dwc_otg
[177625.074419] usb 1-1.2: New USB device found, idVendor=046d, idProduct=08da
[177625.074434] usb 1-1.2: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[177625.076815] gspca_main: gspca_zc3xx-2.14.0 probing 046d:08da
[177626.489952] input: gspca_zc3xx as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.2/input/input4
Atencio : no hi ha "registered new interface driver gspca_zc3xx" -
tldp HOWTO
Amb la comanda lsusb :
sag@odin:~/express-sendfile $ lsusb
Bus 001 Device 008: ID 046d:08da Logitech, Inc. QuickCam Messanger
NGS XpresCam 300
Specs :
- sensor : CMOS 300 Kpx
- microfono incluido
- resolucion : VGA
- formats : imatge 8 Mpx, video 5 Mpx
-
manual
[pdf]
/var/log/dmesg :
[ 3868.212178] usb 1-1-port2: disabled by hub (EMI?), re-enabling...
[ 3868.212210] usb 1-1.2: USB disconnect, device number 4
[ 3868.522116] usb 1-1.2: new high-speed USB device number 5 using dwc_otg
[ 3868.634289] usb 1-1.2: New USB device found, idVendor=1871, idProduct=0142
[ 3868.634311] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[ 3868.634323] usb 1-1.2: Product: USB2.0 Camera
[ 3868.634336] usb 1-1.2: Manufacturer: AVEO Technology Corp.
[ 3868.635905] uvcvideo: Found UVC 1.00 device USB2.0 Camera (1871:0142)
[ 3868.637469] input: USB2.0 Camera as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.2/1-1.2:1.0/input/input1
[ 3868.912113] usb 1-1.2: 3:1: cannot get freq at ep 0x84
[ 3868.913243] usb 1-1.2: Warning! Unlikely big volume range (=8191), cval->res is probably wrong.
[ 3868.913260] usb 1-1.2: [3] FU [Mic Capture Volume] ch = 1, val = 0/8191/1
UVC homepage,
UVC FAQs,
quirks
pi@raspall:~/semafor $ modinfo uvcvideo
filename: /lib/modules/4.1.18-v7+/kernel/drivers/media/usb/uvc/uvcvideo.ko
version: 1.1.1
license: GPL
description: USB Video Class driver
author: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
srcversion: C9B0F67E59368B487C67523
alias: usb:v*p*d*dc*dsc*dp*ic0Eisc01ip00in*
depends: videodev,videobuf2-core,media,videobuf2-vmalloc
intree: Y
vermagic: 4.1.18-v7+ SMP mod_unload modversions ARMv7
parm: clock:Video buffers timestamp clock
parm: nodrop:Don't drop incomplete frames (uint)
parm: quirks:Forced device quirks (uint)
parm: trace:Trace level bitmask (uint)
parm: timeout:Streaming control requests timeout (uint)
Fix : "echo 'options uvcvideo quirks=0x100' | sudo tee -a /etc/modprobe.d/(50-)uvcvideo.conf".
sudo rmmod uvcvideo
sudo modprobe uvcvideo nodrop=1 timeout=6000 quirks=0x80
USB devices list - see vendor ID (VID) and product ID (PID) :
pi@raspall:~ $ lsusb
Bus 001 Device 005: ID 1871:0142 Aveo Technology Corp.
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
You can update device list with sudo update-usbids
Modules:
pi@raspall:/var/log $ lsmod
Module Size Used by
bnep 10336 2
hci_uart 13533 1
btbcm 4196 1 hci_uart
bluetooth 317981 22 bnep,btbcm,hci_uart
evdev 10278 2
uvcvideo 71643 0
snd_usb_audio 114378 2
snd_usbmidi_lib 19690 1 snd_usb_audio
snd_hwdep 5595 1 snd_usb_audio
videobuf2_vmalloc 5187 1 uvcvideo
snd_rawmidi 18300 1 snd_usbmidi_lib
videobuf2_memops 1518 1 videobuf2_vmalloc
snd_seq_device 3445 1 snd_rawmidi
videobuf2_core 34325 1 uvcvideo
v4l2_common 3777 1 videobuf2_core
videodev 121179 3 uvcvideo,v4l2_common,videobuf2_core
media 11501 2 uvcvideo,videodev
brcmfmac 177546 0
brcmutil 5501 1 brcmfmac
cfg80211 389253 1 brcmfmac
rfkill 16036 4 cfg80211,bluetooth
snd_bcm2835 19802 3
bcm2835_gpiomem 2860 0
bcm2835_rng 1763 0
snd_pcm 73442 2 snd_bcm2835,snd_usb_audio
snd_timer 18792 1 snd_pcm
snd 50779 20 snd_bcm2835,snd_usb_audio,snd_hwdep,snd_timer,snd_pcm,snd_rawmidi,snd_usbmidi_lib,snd_seq_device
uio_pdrv_genirq 2944 0
uio 7753 1 uio_pdrv_genirq
i2c_dev 5671 0
fuse 80694 3
ipv6 338574 30
Drivers :
pi@raspall:~ $ v4l2-ctl --list-formats - list all the video modes supported by camera
ioctl: VIDIOC_ENUM_FMT
Index : 0
Type : Video Capture
Pixel Format: 'YUYV'
Name : YUV 4:2:2 (YUYV) --- uncompressed
Te problemes de sincronisme vertical en gravar fotos a fitxer.
dwc_otg.speed=1 ?
Pregunto al foro
openCV,
StackOverflow
It is a UVC device :
pi@raspall:~ $ lsusb -d 1871:0142 -v | grep "14 Video"
Couldn't open device, some information will be missing
bFunctionClass 14 Video
bInterfaceClass 14 Video
bInterfaceClass 14 Video
bInterfaceClass 14 Video
bInterfaceClass 14 Video
bInterfaceClass 14 Video
bInterfaceClass 14 Video
bInterfaceClass 14 Video
Debug :
- enable trace : sudo echo 0xffff > /sys/module/uvcvideo/parameters/trace
- reproduce the problem - driver prints message to kernel log
- disable trace : sudo echo 0 > /sys/module/uvcvideo/parameters/trace
- capture log : dmesg > dmesg.log
We have :
[223665.555829] uvcvideo: uvc_v4l2_open
[223665.555870] uvcvideo: uvc_v4l2_release
[223665.555961] uvcvideo: uvc_v4l2_open
[223665.557180] uvcvideo: Trying format 0x56595559 (YUYV): 640x480.
[223665.557189] uvcvideo: Using default frame interval 33333.3 us (30.0 fps).
[223665.559972] uvcvideo: uvc_v4l2_mmap
[223665.560130] uvcvideo: uvc_v4l2_mmap
[223665.560262] uvcvideo: uvc_v4l2_mmap
[223665.560430] uvcvideo: uvc_v4l2_mmap
[223665.560861] uvcvideo: Device requested 3060 B/frame bandwidth.
[223665.560869] uvcvideo: Selecting alternate setting 5 (3060 B/frame bandwidth).
[223665.561693] uvcvideo: Allocated 5 URB buffers of 32x3060 bytes each.
[223665.561735] uvcvideo: uvc_v4l2_poll
[223665.914706] uvcvideo: Frame complete (overflow).
[223665.914732] uvcvideo: Dropping payload (out of sync).
[223665.914738] uvcvideo: Dropping payload (out of sync).
[223665.914743] uvcvideo: Dropping payload (out of sync).
[223665.914754] uvcvideo: frame 1 stats: 0/2540/2799 packets, 0/0/2799 pts (!early initial), 2798/2799 scr, last pts/stc/sof 3796600832/3912817680/1695
[223665.916385] uvcvideo: uvc_v4l2_poll
[223665.916425] uvcvideo: USB2.0 Camera: PTS 3796600832 y 1908.122177 SOF 1908.122177 (x1 2261855191 x2 2263715498 y1 249954304 y2 251985920 SOF offset 101)
[223665.916437] uvcvideo: USB2.0 Camera: SOF 3956.122177 y 1252222843 ts 223663.444171 buf ts 223662.903919
[223665.946863] uvcvideo: Frame complete (EOF found).
[223665.946889] uvcvideo: frame 2 stats: 8/9/267 packets, 0/0/267 pts (early initial), 266/267 scr, last pts/stc/sof 1097633536/3913819095/1712
[223665.982593] uvcvideo: Frame complete (EOF found).
[223665.982618] uvcvideo: frame 3 stats: 8/9/266 packets, 0/0/266 pts (early initial), 265/266 scr, last pts/stc/sof 1098633536/3914816760/1729
[223666.014721] uvcvideo: Frame complete (EOF found).
[223666.014747] uvcvideo: frame 4 stats: 9/10/267 packets, 0/0/267 pts (early initial), 266/267 scr, last pts/stc/sof 1099633536/3915818175/1745
[223666.020738] uvcvideo: uvc_v4l2_release
Sent to
linux-uvc-devel
Tried to reduce compression :
cv2.imwrite ( szFN, frame, [cv2.cv.CV_IMWRITE_PNG_COMPRESSION, 0] )
Tried changing file type to JPEG, no luck
GPIO 40-pin connector - General Purpose I/O
A powerful feature of the Raspberry Pi is the
row of GPIO (general-purpose input/output) pins
along the top edge of the board
Read GPIO documentation
As well as simple input and output devices, the GPIO pins can be used with a variety of alternative functions,
some are available on all pins, others on specific pins.
Power : the 5 v pins give direct access to the 5 v supply coming from your mains adaptor, less power than used by the Raspberry Pi itself.
A Pi can be powered directly from these pins, and it can also power other 5 v devices.
When using these pins directly, be careful and check your voltages before making a connection because they bypass any safety features,
such as the voltage regulator and fuse which are there to protect your Pi.
If you bypass these with a higher voltage, you could render your Pi inoperable.
Tom's hw
R4 uses MF-MSMF250/X polyfuse or PTC resettable fuses
Open a terminal window and run the command pinout
(from pinout.xyz - see GPIO, SPI, I2C, GPCLK, UART, ...)
input/output voltage and current limits
The GPIO pins can draw 50 mA safely, distributed across all the pins;
an individual GPIO pin can only safely draw 16 mA.
The HDMI port uses 50 mA, the camera module requires 250 mA, ...
The output drives to either 3.3 V (high) or 0 V (low).
Only one driver is shown in the schematic, but in actuality there are several wired in parallel,
with software controlling which are enabled,
so that the output drive impedance can be varied to offer 2 mA to 16 mA current capability, in 2 mA increments.
mosaic ind.,
dibuix
- This is a 3.3 V device. Using 5 V peripherals requires a logic level converter.
- Output
- Maximum total of all pins 50 mA.
- Default 8 mA max per pin. (returns to this configuration after reset)
- Software configurable from 2 mA to 16 mA. Do not source or sink more than what you've configured.
- Don't drive capacitive loads.
- Input
- Threshold of 1.8 V
- Maximum 0.5 mA
- Use a 10 K resistor to ensure that current from a 3.3 V source cannot exceed 0.5 mA ( 3.3 V / 10 KΩ = 0.33 mA )
RaspberryPi StackExchange
special GPIO pins
Certain GPIO pins also have alternate functions that allow them to interface with different kinds of devices that use the I2C, SPI or UART protocols :
- PWM (pulse-width modulation)
- software PWM available on all pins
- hardware PWM available on GPIO12, GPIO13, GPIO18, GPIO19
- SPI - Serial Peripheral Interface
- SPI0: MOSI (GPIO10); MISO (GPIO9); SCLK (GPIO11); CE0 (GPIO8), CE1 (GPIO7)
- SPI1: MOSI (GPIO20); MISO (GPIO19); SCLK (GPIO21); CE0 (GPIO18); CE1 (GPIO17); CE2 (GPIO16)
- I2C - Inter-Integrated Circuit
- Data: (GPIO2); Clock (GPIO3)
- EEPROM Data: (GPIO0); EEPROM Clock (GPIO1)
- Serial
The
Raspberry Pi GPIOs
can be controlled using many programming languages -
samples
El "Python module to control the GPIO on a Raspberry Pi" mes popular és
python rpi gpio - wiki amb exemples
Ves amb compte amb la numeració dels pins que n'hi ha dues : la BCM i la BOARD.
Per fer-ho anar amb node ens cal
rpi-gpio package.
Python : BCM versus BOARD pin notation
When using the RPi.GPIO library in Python you have to call
import RPi.GPIO as GPIO
and then
GPIO.setmode(GPIO.BOARD)
or
GPIO.setmode(GPIO.BCM)
What is the difference ?
- The GPIO.BOARD option specifies that you are referring to the pins by the number of the pin in the plug, from 1 to 40.
This is, the numbers printed on the board.
- The GPIO.BCM option means that you are referring to the pins by the "Broadcom SOC channel" number.
Those numbers are purely "virtual".
Good tutorial
Python : run time error "no access top /dev/mem"
If you get "No access to /dev/mem. Try running as root!", just add the user to the gpio group and reboot.
Command is "sudo adduser sebas gpio"
Verify it using "id" command after reboot.
node.js : BCM versus RPI pin notation
Please note that there are two different and confusing ways to reference a channel;
either using the Raspberry Pi or the BCM/SoC naming schema.
setMode(mode) - Sets the channel addressing schema.
Mode: Specify either Raspberry Pi or SoC/BCM pin schemas, by passing MODE_RPI or MODE_BCM. Defaults to MODE_RPI.
Internal pull-ups and pull-downs
At "setup" time, indicate you need them :
GPIO.setup(port_or_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # we’re using pull-down
GPIO.setup(port_or_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # we’re using pull-up
Pull up / down dels pins del GPIO
Compte !
See
document, page 102 and 103.
Pull ...
- high : GPIO 0-8, 34-36, 46-53
- low : GPIO 9-27, 30-33, 38-43
Display GPIO version
Easy :
sag@odin:~/gpio_python $ sudo python
Python 2.7.9 (default, Sep 26 2018, 05:58:52)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import RPi.GPIO as GPIO
>>> GPIO.VERSION
'0.6.3'
>>>
Or code this :
#!/usr/bin/env python
import RPi.GPIO as GPIO
print "Versio GPIO =", GPIO.VERSION # mostrar la versio de GPIO
How to connect GPIO to a breadboard / protoboard
Per conectar el GPIO del raspberry a una Adle/Board nº 8 cal un cable pla amb un conector per breadboard
Aliexpress "RPi GPIO Breakout Expansion Board + 40pin Flat Ribbon Cable For Raspberry Pi 3 2 Model B & B+" : 2,64 $
- 1pcs GPIO 40P Breakout Board For Raspberry Pi 2 Mode B & B+
- 1pcs 20cm FC40 40pin Flat Rainbow Ribbon Cable
PWM
Sure we know what PWM is
We will be using the
RPi.GPIO library
which provides software PWM utility. Here are the main functions:
p = GPIO.PWM(channel, frequency) # create a PWM instance
p.start(dc) # start PWM - dc is the duty cycle (0.0 <= dc <= 100.0)
p.ChangeFrequency(freq) # change the frequency - freq is the new frequency in Hz
p.ChangeDutyCycle(dc) # change the duty cycle -0.0 <= dc <= 100.0
p.stop() # stop PWM
PWM links
I2C interface
Hem de conectar 4 pins :
- (pin 39) GND
- (pin 2) Vcc 5 volts {+ 0,1 uF decoupling capacitor to GND}
- (pin 3) SDA {+ pull up resistor}
- (pin 5) SCL {+ pull up resistor}
Enable I2C :
$ sudo raspi-config
5 interfacing options
P5 I2C enable
select "enable"
$ sudo reboot
sag@odin:~ $ ls /dev/*i2c*
/dev/i2c-1
Install i2c-tools :
apt-get update ; fer sovint
apt-get install i2c-tools
sudo apt-get install python-smbus -
smbus module
Display available interfaces :
sag@odin:~ $ i2cdetect -l
i2c-1 unknown bcm2835 I2C adapter N/A
Display devices on that bus : $ i2cdetect -y 1 {i2cdetect -r 1}
sag@odin:~ $ sudo i2cdetect -y 1
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
read temperature : i2cget -y 0 0x48 0 b
The I2C connection needs 2 pull-up resistors to hold the bus high
(R1, R2), 2K-10K should work.
C1 is a 0.1uF decoupling capacitor, entre positiu i GND
Raspberry Pi I2C Python-Writing
rspi and i2c and python
Good article :
TC74 and us
TC74 homepage and
datasheet
The TC74 is a serially accessible, digital temperature sensor particularly suited for low cost and small form-factor applications.
Temperature data is converted from the onboard thermal sensing element and made available as an 8-bit digital word.
Temperature resolution is 1°C.
Conversion rate is a nominal 8 samples/sec.
During normal operation, the quiescent current is 200 μA.
Eight SMBus/I2C addresses are programmable for the TC74, which allows for a multi-sensor configuration.
TC74A0-3.3VCT 1001 000 V0
TC74A1-3.3VCT 1001 001 V1
TC74A2-3.3VCT 1001 010 V2
TC74A3-3.3VCT 1001 011 V3
TC74A4-3.3VCT 1001 100 V4
TC74A5-3.3VCT 1001 101* V5
TC74A6-3.3VCT 1001 110 V6
TC74A7-3.3VCT 1001 111 V7
The TC74 is internally programmed to have a default SMBus/I2C address value of 1001 101b.
Això és hexadecimal pero li falta un bit ...
The TC74’s write address is 0x9A, and the read address 0x9B.
It has two, one-byte registers. Register address 0 holds the temperature reading, register 1 holds the configuration settings.
Some good explanation [***]
Some python code (using Adafruit_I2C)
and some c code - i2c_temp.c
Display the temperature using
Apache
Buzzwords : "i2cdetect", "i2cget" - see
i2c bus
TC74 at R3
We want to serve a page with actual temperature, so we use R3.
We start with
sag@odin:~/python/i2c $ i2cdetect -l
i2c-1 unknown bcm2835 I2C adapter N/A
Then we go (TC74 connected with 2 pull-ups) :
sag@odin:~/python/i2c $ sudo i2cdetect -y 1
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- 4a -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
Now that we know the TC74 i2c address, we can code :
sag@odin:~/python/i2c $ cat tc74_read.py
#!/usr/bin/env python3
# this code reads a TC74 at i2c address 0x4A
# https://learn.sparkfun.com/tutorials/tmp102-digital-temperature-sensor-hookup-guide
# https://learn.sparkfun.com/tutorials/python-programming-tutorial-getting-started-with-the-raspberry-pi/experiment-4-i2c-temperature-sensor
import time
import smbus
# i2c channel. used in init
i2c_ch = 1
# TC74A2 address on the I2C bus is 0x4A
i2c_tc74 = 0x4A
# Register addresses
reg_temp = 0x00
reg_config = 0x01
# Calculate the 2's complement of a number
def twos_comp(val, bits):
if (val & (1 << (bits - 1))) != 0:
val = val - (1 <<; bits)
return val
# Read temperature registers and calculate Celsius
def read_temp( i2c_addr ):
# Read temperature registers
val = bus.read_i2c_block_data( i2c_addr, reg_temp, 2)
# NOTE: val[0] = MSB byte 1, val [1] = LSB byte 2
# print ("!shifted val[0] = ", bin(val[0]), "val[1] = ", bin(val[1]))
temp_c = (val[0] << 4) | (val[1] >> 4)
# print (" shifted val[0] = ", bin(val[0] << 4), "val[1] = ", bin(val[1] >> 4))
# print (bin(temp_c))
# Convert to 2s complement (temperatures can be negative)
temp_c = twos_comp(temp_c, 12)
# Convert registers value to temperature (C)
temp_c = temp_c * 0.0625
return temp_c
# Initialize I2C (SMBus)
bus = smbus.SMBus(i2c_ch)
# Print out temperature every second
while True:
temperatura = read_temp( i2c_tc74 )
print( ">>> ", round(temperatura, 2), "C" )
time.sleep(1)
If we get "ImportError: No module named 'smbus'" we do ...
sudo apt-get update ; fer sovint
sudo apt-get install i2c-tools
sudo apt-get install python-smbus
sag@odin:~/python/i2c $ sudo pip3 install smbus
Downloading/unpacking smbus
Downloading smbus-1.1.post2-cp34-cp34m-linux_armv7l.whl (41kB): 41kB downloaded
Installing collected packages: smbus
Successfully installed smbus
Cleaning up...
sudo adduser sebas gpio
sag@odin:~/python/i2c $ sudo adduser sag i2c
Adding user `sag' to group `i2c' ...
Adding user sag to group i2c
Done.
And here is the result :
sag@odin:~/python/i2c $ ./tc74_read.py
>>> 28.94 C
>>> 29.94 C
>>> 29.94 C
>>> 28.94 C
Now we want to display the local temperature on a client browser, using nodejs - see TC74 details
SPI interface
The SPI bus (or Serial Peripheral Interface bus) is a synchronous serial data link originally created by motorola.
For more information about SPI please refer to this
wikipedia
The Serial Peripheral Interface (SPI) is a communication protocol used to transfer data between micro-computers like the Raspberry Pi and peripheral devices.
SPI uses 4 separate connections to communicate with the target device.
These connections are the serial clock (CLK), Master Input Slave Output (MISO), Master Output Slave Input (MOSI) and Chip Select (CS).
The default Linux driver is
spi_bcm2708
Raspberry documentation
La Raspberry Pi cuenta con tres interfaces maestro SPI (SPI0, SPI1 y SPI2) aunque solo una de ellas (SPI0) es visible para los modelos originales
y dos de ellas (SPI0 y SPI1) para los modelos con conector J8 de 40 pines.
Cada una de estas interfaces cuenta con dos líneas de selección de destino (CE0 y CE1).
De ellas SPI0 es más evolucionada, puesto que permite DMA (acceso directo a memoria).
SPI0 está diseñada para transferencias de alta velocidad (reloj de hasta 125Mhz) sin producir una carga significativa para el procesador.
Sin embargo SPI1 no tiene posibilidad de usar DMA y solo dispone de una pequeña FIFO de cuatro palabras de 32 bits
git books
The Raspberry Pi is equipped with one SPI bus that has 2 chip selects.
The SPI master driver is disabled by default on Raspberry Pi OS.
To enable it, use raspi-config, or ensure the line "dtparam=spi=on" isn't commented out in /boot/config.txt, and reboot.
If the SPI driver was loaded, you should see the device /dev/spidev0.0
The SPI bus is available on the P1 Header:
SPI-0 SPI-1
------ ------
MOSI P1-19 MISO P1-35
MISO P1-21 P1-38 MOSI
SCLK P1-23 P1-24 CE0 P1-40 SCLK
GND P1-25 P1-26 CE1 CE1 P1-11 P1-12 CE0
P1-36 CE2
See nice pinout
Enable SPI interface :
$ sudo raspi-config
5 Interfacing options
P4 SPI
select "enable"
$ sudo reboot
sag@odin:~ $ ls /dev/*spi*
/dev/spidev0.0 /dev/spidev0.1
sebas@pi0alby:~/python $ ls /dev/*sp*
0 crw-rw---- 1 root spi 153, 0 Jun 25 17:09 /dev/spidev0.0
0 crw-rw---- 1 root spi 153, 1 Jun 25 17:09 /dev/spidev0.1
All the devices /dev/spidev0.{x} will share the same clock and I/O lines so the only difference is the chip select -
from
pdf
Put a wire between MOSI and MISO, pins 19 and 21
$ wget https://raw.githubusercontent.com/raspberrypi/linux/rpi-3.10.y/Documentation/spi/spidev_test.c
$ gcc -o spidev_test spidev_test.c
sag@odin:~/spi_test $ sudo ./spidev_test -D /dev/spidev0.0
spi mode: 0
bits per word: 8
max speed: 500000 Hz (500 KHz)
FF FF FF FF FF FF
40 00 00 00 00 95
FF FF FF FF FF FF
FF FF FF FF FF FF
FF FF FF FF FF FF
DE AD BE EF BA AD
F0 0D
Igual que aquest senyor,
SPI basics amb un bon esquema.
SPI1 enable
Add this to /boot/config.txt and reboot
dtoverlay=spi1-3cs
It should enable auxiliary SPI with SPI1 CE2 (GPIO16) for channel select
The pins were like this:
SDA/CE2: 36
MISO: 35
MOSI: 38
SCKL: 40
RESET: 13
use SPI0 and SPI1 ,
/boot/overlays/README,
pinout
tech detail
Com tenir
5 esclaus i loopback en python i
esquemes de temps, etc {*****}
Shell test
# Write binary 1, 2 and 3
echo -ne "\x01\x02\x03" > /dev/spidev0.0
SPI driver speed test , from
url
Loopback test
This can be used to test SPI send and receive.
It uses the Linux spidev driver to access the bus.
Put a wire between MOSI and MISO.
$ wget https://raw.githubusercontent.com/raspberrypi/linux/rpi-3.10.y/Documentation/spi/spidev_test.c
gcc -o spidev_test spidev_test.c
./spidev_test -D /dev/spidev0.0
pigs program, pigpio library
$ sudo pigpiod
pigs spio 0 50000 0
pigs spix 0 1 2 3 4 5 6 7 8 9 10 11
From abyz.me.uk
SPI from python
Install Python spidev module
Python params
bits_per_word
cshigh
loop - Set the "SPI_LOOP" flag to enable loopback mode
no_cs - Set the "SPI_NO_CS" flag to disable use of the chip select (although the driver may still own the CS pin)
lsbfirst
max_speed_hz ( > 0 !!! )
mode - SPI mode as two bit pattern of clock polarity and phase [CPOL|CPHA], min: 0b00 = 0, max: 0b11 = 3
threewire - SI/SO signals shared
Compte que el C te menys params !
url
Compte amb els methodes : xref vs xfre2 (CS)
Usage
import spidev
spi = spidev.SpiDev()
spi.open(bus, device)
to_send = [0x01, 0x02, 0x03]
spi.xfer(to_send)
spi.close()
Python spidev.SpiDev() examples
raspall software
From scratch we have :
pi@raspberrypi-llovet:~ $
cat /etc/debian_version
8.0
pi@raspberrypi-llovet:~ $
uname -a ; kernel version
Linux raspberrypi-llovet 4.1.18-v7+ #846 SMP Thu Feb 25 14:22:53 GMT 2016 armv7l GNU/Linux
pi@odin:~/logs $ uname -a
Linux odin 4.4.11-v7+ #888 SMP Mon May 23 20:10:33 BST 2016 armv7l GNU/Linux
pi@raspberrypi-llovet:~ $
ssh -V
OpenSSH_6.7p1 Raspbian-5+deb8u2, OpenSSL 1.0.1t 3 May 2016
pi@raspberrypi-llovet:~ $
gcc --version
gcc (Raspbian 4.9.2-10) 4.9.2
pi@raspberrypi-llovet:~ $
git --version
git version 2.1.4
pi@raspberrypi-llovet:~ $
python --version
Python 2.7.9
pi@raspberrypi-llovet:~ $
node -v
v0.10.29 ; quite old, isn't it ?
LTS is 4.4.5, and "current" is 6.2.2
Maybe we have to install :
pi@raspberrypi-llovet:~ $ sudo apt-get update ; update all software, sovint
pi@raspberrypi-llovet:~ $ sudo apt-get install python-dev ; install the Python Development toolkit that RPi.GPIO requires
pi@raspberrypi-llovet:~ $ sudo apt-get install python-rpi.gpio ; install Rpi.GPIO itself
$ sudo apt-get install python3-rpi.gpio ; python3
pi@raspberrypi-llovet:~ $ sudo apt-get install -y nodejs ; update
nodejs
sudo apt-get install tofrodos
sudo ln -s /usr/bin/fromdos /usr/bin/dos2unix
sudo npm install -g express
pi@raspberrypi-llovet:~ $ sudo npm remove -g express
sudo npm install express --save ; local directory install & update
package.json
sudo npm install express-session --save ;
Manual install on "Raspberry Pi 3" :
wget https://nodejs.org/dist/v4.3.2/node-v4.3.2-linux-armv6l.tar.gz ; mind we have an ARM cpu
tar -xvf node-v4.3.2-linux-armv6l.tar.gz
cd node-v4.3.2-linux-armv6l ; copy to /usr/local
Last version is 6.2.2
With clean-up :
pi@raspberrypi:~ $ node -v
v0.10.29 # the one I have !
pi@raspberrypi:~ $ sudo su - # lets be root
root@raspberrypi:~ # apt-get remove nodered -y
root@raspberrypi:~ # apt-get remove nodejs nodejs-legacy -y
root@raspberrypi:~ # apt-get remove npm -y # if you installed npm
root@raspberrypi:~ # curl -sL https://deb.nodesource.com/setup_5.x | sudo bash -
root@raspberrypi:~ # apt-get install nodejs -y
root@raspberrypi:~ # node -v
v5.11.1 # a lot better !
root@raspberrypi:~ # npm -v
3.8.6
Understand npm folders
ttyN (1..6)
TTY is shorthand for Teletypewriter.
CTRL + ALT + F1 –> TTY1
CTRL + ALT + F2 –> TTY2
CTRL + ALT + F3 –> TTY3
CTRL + ALT + F4 –> TTY4
CTRL + ALT + F5 –> TTY5
CTRL + ALT + F6 –> TTY6
using Putty
Using Putty to access Raspbian, we can use Copy and Paste as follows :
- copy : just "mark" the text dragging the cursor
- paste : use "SHIFT" + "Insert"
I have Debian "jessie"
Display :
pi@odin:~ $ cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 8 (jessie)"
NAME="Raspbian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"
ID=raspbian
ID_LIKE=debian
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"
pi@odin:~ $ cat /etc/rpi-issue
Raspberry Pi reference 2016-05-27
Generated using pi-gen, https://github.com/RPi-Distro/pi-gen, 5add7283d4db4eaad785de41a6750e909e5a04cf, stage4
Aixo corre un
systemd
Linus Torvalds, Chief architect of Linux kernel, feels attitude of key developer of systemd towards users and bug reports do not seems ok.
It was also reported that systemd philosophy is weird and a foreign way to control system processes.
The same has been recorded from Patric Volkerding and other notable Linux Users and Developers as well as over online forum, time-to-time.
Fes servir "systemctl poweroff", "reboot", etc.
Jo sempre faig un "sync" abans, si puc.
Raspbian update
20210125 :
sag@odin:~ $ sudo apt-get update
sag@odin:~ $ sudo apt-get upgrade
$ cat /var/log/apt/term.log
$ cat /var/log/dpkg.log
sag@odin:~ $ cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 9 (stretch)"
NAME="Raspbian GNU/Linux"
VERSION_ID="9"
VERSION="9 (stretch)"
VERSION_CODENAME=stretch
ID=raspbian
ID_LIKE=debian
Startup - how to use rc.local
If we want to start a command, an APP or whatever at startup time, place it in /etc/rc.local,
but indirectly, starting an own shell in background :
pi@odin:~ $ cat /etc/rc.local
#!/bin/sh -e
/usr/local/bin/odin_restart &
exit 0
cron
Volem fer neteja i enviar la nostra IP cada dia a les 4 de la matinada.
- "sudo su -" {no cal si posem "sudo" a cada comanda}
- edit crontab : sudo crontab -e
- indicate job to run and the time schedule
# m h dom mon dow command
0 4 * * * /home/pi/eines/cron_feina_send_email.sh *** removed 20200802 ***
*/15 * * * * /home/pi/eines/
cron_feina_15_min.sh
- output and errors are sent using mail to this user
- view scheduled tasks : sudo crontab -l
- restart service to read new configuration by sudo /etc/init.d/cron restart
Services, events and scripts
Raspbian uses systemd structure.
What script is lauched at what event ?
- /etc/rc.local : this script is executed at the end of each multiuser runlevel
Dont use it - oldie. Copy /etc/init.d/Skeleton to a new init script and use insserv
- /etc/network/if-up.d/ : every script (without .sh extension) in this directory is executed when link comes up
- .bashrc : your program will run on boot and also every time when a new terminal is opened, or when a new SSH connection is made
- /etc/init.d : read files in /usr/share/doc/sysv-rc directory
/etc/init.d
We have one at Pi0 startup
DUC & noip2
How to Install the Dynamic Update Client on Linux -
the below commands should be executed from a terminal window after logging in as the “root” user.
You can become the root user from the command line by entering “sudo su -” followed by the root password on your machine.
cd /usr/local/src
wget http://www.no-ip.com/client/linux/noip-duc-linux.tar.gz
tar xzf noip-duc-linux.tar.gz
cd noip-2.1.9-1
make
make install
To configure the Client, as root again (or with sudo) issue the below command:
$ /usr/local/bin/noip2 -C (dash capital C, this will create the default config file)
You will then be prompted for your username and password for No-IP, as well as which hostnames you wish to update.
Now that the client is installed and configured, you just need to launch it.
Simply issue this final command to launch the client in the background:
$ /usr/local/bin/noip2
Read the README file in the no-ip-2.1.9 folder for instructions on how to make the client run at startup.
noip2 verify, trace and force
To verify it works, do "host raspall.hopto.org"
The IP has to be the same as of "curl -s icanhazip.com"
sag@odin:~ $ host myraspiodin.hopto.org
myraspiodin.hopto.org has address 83.38.148.250
sag@odin:~ $ curl -s icanhazip.com ; curl -m 2 -s http://checkip.amazonaws.com
83.38.148.250
To verify it is running, do "ps -ef | grep noip2" {kill it if it is to be restarted}
To display a trace of its work, do "cat /var/log/syslog | grep noip2"
sag@odin:~ $ sudo cat /var/log/syslog | grep noip2
Sep 5 20:27:25 localhost noip2[5648]: v2.1.9 daemon started with NAT enabled
Sep 5 20:27:28 localhost noip2[5648]: myraspiodin.hopto.org set to 83.38.148.250
To force noip2 to update, do "sudo /usr/local/bin/noip2 -c /usr/local/etc/no-ip2.conf" (after killing it, if neccessary)
RASPALL startup : DUC
noip2 + llovetbrossa : raspall.hopto.org
pi@odin:/etc $ cat /usr/bin/raspall_restart {from /etc/rc.local}
time_name=`date +"h%H:m%M"`
echo "(7) (" $date_name "-" $time_name ") start NOIP2 client to update IP at HOPTO" >> $lfn
/usr/local/bin/noip2 -c /usr/local/etc/no-ip2.conf >> $lfn
echo "(8) (" $date_name "-" $time_name ") verify NOIP2 client is running" >> $lfn
host raspall.hopto.org >> $lfn
ODIN startup : DUC
noip2 + campdefabes : myraspiodin.hopto.org
pi@odin:/etc $ cat /usr/bin/odin_restart {from /etc/rc.local}
time_name=`date +"h%H:m%M"`
echo "(7) (" $date_name "-" $time_name ") start NOIP2 client to update IP at HOPTO" >> $lfn
/usr/local/bin/noip2 -c /usr/local/etc/no-ip2.conf >> $lfn
echo "(8) (" $date_name "-" $time_name ") verify NOIP2 client is running" >> $lfn
host myraspiodin.hopto.org >> $lfn
SAG's "odin" hw & sw
- NOOBS v 1.9.2 - url 3.0 {20190211}
- hostname := "odin" ;
- sistema operatiu
pi@odin:~ $ cat /etc/issue
Raspbian GNU/Linux 8 \n \l
- u = "pi", p = "<ya_3>.2016" {8 chars} ; u2 = "sag", p2 = "<ya_3>2016" {7 chars} ;
pi@odin:/ $ sudo passwd root ; set password for "root" user - not neccessary - use "sudo"
Enter new UNIX password:
- xarxa wifi :
pi@odin:/ $ /sbin/iwgetid
wlan0 ESSID:"enxaneta"
- eth0 IP = 192.168.1.13, wlan0 IP = 192.168.1.123
Edit /etc/dhcpcd.conf to include
pi@odin:~ $ cat /etc/dhcpcd.conf
interface eth0
static ip_address=192.168.1.13/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 8.8.4.4
interface wlan0
static ip_address=192.168.1.123/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 8.8.4.4
TCPIP cfg
R3,
R4,
PiZero.
- ports : veure obrir,
veure ports oberts
- sudo apt-get update ; sovint
- sudo apt-get install python-dev
- sudo apt-get install python-rpi.gpio {diu que no cal}
- sudo su -
- apt-get remove nodered -y
- apt-get remove nodejs nodejs-legacy -y
- apt-get remove npm -y
- curl -sL https://deb.nodesource.com/setup_5.x | sudo bash - {avis deprecated}
See
LTS,
distros
- apt-get install nodejs -y
- scp pi@79.156.26.75:9008:/home/pi/.bash_aliases .
- scp pi@79.156.26.75:9008:/etc/motd .
- clone project :
pi@odin:~$ git clone https://github.com/sebastianet/semafor.git
Cloning into 'semafor'...
remote: Counting objects: 175, done.
remote: Compressing objects: 100% (27/27), done.
remote: Total 175 (delta 10), reused 0 (delta 0), pack-reused 145
Receiving objects: 100% (175/175), 664.31 KiB | 556.00 KiB/s, done.
Resolving deltas: 100% (77/77), done.
Checking connectivity... done.
- npm install - uses package.json i omple "/home/pi/semafor/node_modules/"
- "id" command says "+++ app SEM SAG. Versio [v1.1.h]. HN [odin]. usr [undefined]. GYR [18/15/16]. TimeStamp [21:42:49]."
- cant run "9_webcam.py" - "sudo python -m pip install --upgrade numpy"
- sudo apt-get install libhighgui2.4 libopencv-imgproc2.4 libopencv-core2.4 python-opencv
- sudo apt-get install python-opencv
- sudo apt-get install python-numpy
- (webcam:10881): Gtk-WARNING **: cannot open display: {fixed by "export DISPLAY=:0"}
- sudo apt-get install mailutils {in fact, "mail" is here}
- sudo apt-get install ssmtp
- scp pi@79.156.26.75:9008:/etc/ssmtp/ssmtp.conf .
- do ssh without pwd
sag@odin:~ $ sudo apt-get install sshpass
odin's sw versions
node -v : v5.12.0
npm -v : 3.8.6
motd and automatic commands
. --- /etc/motd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. .
. directoris .
. IP externa IP interna .
. /home/sag/express-sendfile .
. server.js - sequencia de fotos webcam - http://myraspiodin.hopto.org:8815/ http://odin:2415 *** .
. /home/sag/gpio_python .
. entrada.py + wsm.js .
. /home/sag/Raspberry-Pi-Simple-Web-GPIO-GUI .
. app.js - mando remot dels pins GPIO - http://myraspiodin.hopto.org:9009/ http://odin:1212 *** .
. app.js - mando remot dels pins GPIO - http://myraspiodin.hopto.org:7171/ http://odin:1313 *** .
. /home/sag/sounds .
. /home/pi/llisco .
. - http://myraspiodin.hopto.org:9035 http://odin:3535 *** .
. /home/pi/semafor .
. 1_sem.js - http://myraspiodin.hopto.org:9009/ http://odin:1212 .
. /home/pi/sendemail .
. /home/pi/timer .
. 1_gen_html.js http://odin:3001 -> pomnia .
. - myraspiodin.hopto.org:9022 odin:22 .
. .
. init .
. /etc/rc.local -> /usr/bin/odin_restart -> /home/pi/logs/rc.local.log i /home/pi/logs/engegades.log .
. /usr/bin/node /home/sag/Raspberry-Pi-Simple-Web-GPIO-GUI/bin/www /home/sag/logs/rmtc.log .
. /home/sag/express-sendfile/server.js photo_server.log .
. /home/sag/tc74/servidor.js temperature.log .
. /home/sag/python/telegram/missatge_a_telegram.sh -> client.py .
. .
. crontab .
. */15 * * * * /home/pi/eines/cron_feina_15_min.sh -> apunta un munt de dades al LOG .
. log /home/pi/logs/cron_feina_15_min.log .
. 25 * * * * /home/sag/python/tinet/enviar_ip_a_tinet.py >> /home/sag/logs/enviar_ip_a_tinet.log .
. 4 2 * * * /home/sag/python/telegram/missatge_a_telegram.sh .
. 20 1 * * * /home/pi/eines/fer_backup.sh .
. .
. /etc/cron.hourly /home/pi/eines/cron_feina_send_email.sh -> bisc2k9 + llovet amb IP interna i ext .
. log /home/pi/logs/cron_job.log send_emilio.log .
. configuration .
. noip2 - myraspiodin.hopto.org - /usr/local/etc/no-ip2.conf .
. static ip - /etc/dhcpcd.conf .
. tcpdump - installed 20200518 .
. jessie v8 -> stretch v9 -> buster v10: sudo apt-get update + sudo apt-get dist-upgrade .
. .
. --- /etc/motd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
cron al odin
Millor (20200802) enviar la IP cada hora, amb un
/etc/cron.hourly $ sudo ln -s /home/pi/eines/cron_feina_send_email.sh envia_ips
Els scripts amb sortida a fitxer tenen la ruta explicita i la redireccio de errors cap a la sortida (no mail)
# m h dom mon dow command
29 1 2 * * /home/sag/logs/1_netejar.sh
33 5 * * * cd /home/sag/eines/backup && /home/sag/eines/backup/fer_backup.sh
25 * * * * cd /home/sag/python/tinet && /home/sag/python/tinet/enviar_html_a_tinet.py &>> /home/sag/logs/enviar_html_a_tinet.log
4 2 * * * /home/sag/python/telegram/missatge_a_telegram.sh kron
*/3 * * * * /home/sag/eines/wifi_wd.sh
*/2 * * * * cd /home/sag/python/byet && /home/sag/python/byet/wd_a_byet.py &>> /home/sag/logs/wd_a_byet.log
Canvi o backup de la microSD
Tenia una microSD class 10 de 16 GB amb NOOBS ;
tinc una microSD class 10 de 64 GB buida
- extreu img de la sd vella a disc laptop (HD Raw Copy Tool)
- graba imatge a sd nova
- bota el rspi i fes un resize amb
raspi-config,
github
Comandes
< posem la SD vella >
$ sudo fdisk -l veure els discs que hi ha a la maquina
$ sudo mkdir /mnt/sag fem un punt per muntar la particio
$ cd /mnt/sag anem a la particio desti de la imatge
$ sudo umount /dev/sdb desmuntem el disc "origen"
$ sudo dd if=/dev/sdb of=sd.img bs=4M status=progress gravem la imatge de la SD al disc dur
3798+1 records in
3798+1 records out
15931539456 bytes (16 GB) copied, 1812,02 s, 8.8 MB/s
$ ls -al sd.img mostrem el resultat
nicolau@mars:/mnt/sag$ ls
total 1955852
1955844 -rw-r--r-- 1 root root 2002780160 May 16 16:57 sd.img
< posem la SD nova >
nicolau@mars:/mnt/sag$ sudo fdisk -l
Device Boot Start End Sectors Size Id Type
/dev/sdb1 32768 124735487 124702720 59.5G 7 HPFS/NTFS/exFAT
$ sudo dd if=sd.img of=/dev/sdb bs=4M status=progress gravem la imatge a la nova SD
3798+1 records in
3798+1 records out
15931539456 bytes (16 GB) copied, 1580,01 s, 10.1 MB/s
$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/root 14G 5.1G 7.6G 41% /
sebas@filipo$ dd if=/dev/sda | ssh usr@pablito dd of=/dev/sda bs=4M # filipo old, pablito new - card to card
root@pizero$ dd if=/dev/mmcblk0 | ssh nicolau@mars dd of=/tmp/sdimg/imatge.img bs=4M status=progress # pizero old, mars has backup - card to disk
pi0$ sudo raspi-config --expand-rootfs
url
pi0$ sudo reboot now
pi@pi0:~ $ dfh
/dev/root 52G 1.5G 48G 3% /
AskUbuntu
Your partition layout is not currently supported by this tool.
You are probably using NOOBS,
in which case your root filesystem is already expanded anyway.
Use gparted on T60
dd - copy SD - un altre cop
20200723 : Ho pots fer per LAN si no tens dos adaptadors al mateix PC
filipo = ordinador amb la tarja de pizero 16 GB
pablito = ordinador amb la tarja 64 GB
sebas@filipo$ dd if=/dev/sda status=progress | ssh pablito sudo dd of=/dev/sda bs=4MB
R3 amb SD de 2 TB
< posem la SD d 2 TB al adaptador i conectem a MINIE > .
sebas@minie:~$ lsblk veure els discs que hi ha a la maquina
sebas@minie:~/dades/_local_tinet_files$
lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
sda 8:0 0 232,9G 0 disk
└─sda1 8:1 0 232,9G 0 part
sdb 8:16 1 2T 0 disk /media/sebas/6CD0-D0A3
nvme0n1 259:0 0 931,5G 0 disk
├─nvme0n1p1 259:1 0 100M 0 part /boot/efi
├─nvme0n1p2 259:2 0 16M 0 part
├─nvme0n1p3 259:3 0 497,9G 0 part
├─nvme0n1p4 259:4 0 1000M 0 part
└─nvme0n1p5 259:5 0 432,6G 0 part /
sebas@minie:~$ dmesg veure que ha vist el kernel
[ 2163.568651] usb 1-2: new high-speed USB device number 7 using xhci_hcd
[ 2163.717853] usb 1-2: New USB device found, idVendor=1908, idProduct=0226, bcdDevice= 1.11
[ 2163.717860] usb 1-2: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[ 2163.718333] usb-storage 1-2:1.0: USB Mass Storage device detected
[ 2163.718527] scsi host1: usb-storage 1-2:1.0
[ 2164.721334] scsi 1:0:0:0: Direct-Access Generic Mass-Storage 1.11 PQ: 0 ANSI: 2
[ 2164.721987] sd 1:0:0:0: Attached scsi generic sg1 type 0
[ 2165.314589] sd 1:0:0:0: [sdb] 4194304000 512-byte logical blocks: (
2.15 TB/1.95 TiB)
[ 2165.315037] sd 1:0:0:0: [sdb] Write Protect is off
[ 2165.315045] sd 1:0:0:0: [sdb] Mode Sense: 03 00 00 00
[ 2165.315370] sd 1:0:0:0: [sdb] No Caching mode page found
[ 2165.315373] sd 1:0:0:0: [sdb] Assuming drive cache: write through
[ 2165.318457] sd 1:0:0:0: [sdb] Attached SCSI removable disk
< use DISKS to format the SD > .
fdisk -l display availale disks
fdisk /dev/sdb + "n" (add a new partition)
+ "e" (extended) + "p" (print partition table)
+ "w" (write) create /dev/sdb1 - 2,1 TB FAT
sebas@minie:~$ sudo mkfs.vfat -F 32 /dev/sdb1
mkfs.fat 4.2 (2021-01-31)
sebas@minie:~
< use DISKS to mount the SD > .
sebas@minie:~$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sdb 2,0T 32K 2,0T 1% /media/sebas/r3_2tb Properties : filesystem type = W95 FAT32 (LBA)
NOOBS no longer supported - use
Raspberry Pi Imager
Obtenim
imager_1.8.5_amd64.deb
sebas@minie:~/dades/rspi/op_sys$
sudo apt install rpi-imager - compte : instala 1.7.2
We start the imager :
choose Operating System :
Raspberry Pi OS (64-bit) ***
Raspberry Pi OS (32-bit)
Raspberry Pi OS (Legacy, 32-bit)
choose Storage :
generic mass-storage - 2147,5 GB
mounted as /media/sebas/r3_2tb
write
Verifying write failed. Contents of SD card is different from what was written to it.
Ask
forums.raspberrypi.com
Ask
raspberrypi.stackexchange.com {c@g.c}
Use
h2testw (guindous) from
en.lo4d :
download
sebas@minie:~$ dpkg-query -l rpi-imager -
baedlung
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name Version Architecture Description
+++-==============-======================-============-=================================
ii rpi-imager 1.7.2+noembed-0ubuntu1 amd64 Raspberry Pi imaging utility
sebas@minie:~$ sudo apt-get remove rpi-imager
sebas@minie:~$ sudo apt-get purge rpi-imager
go to imager_1.8.5_amd64.deb and "open with" the "GDebi Package installer"
"USB Stick formatter" : filesystem := FAT32 ;
sebas@minie:~$ sudo fdisk /dev/sdb
Welcome to fdisk (util-linux 2.37.2).
Command (m for help): p
Disk /dev/sdb: 1,95 TiB, 2147483648000 bytes, 4194304000 sectors
Disk model: Mass-Storage
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xba92a7d0
Device Boot Start End Sectors Size Id Type
/dev/sdb1 2048 4194303999 4194301952 2T c W95 FAT32 (LBA)
Imager 1.8.5 :
device := Raspberry Pi 3 (models B, A+, B+)
operating system := Raspberry Pi OS (64 bit)
storage := USB stick
*** write successful ***
Tal com surt :
Device Boot Start End Sectors Size Id Type
/dev/sdb1 8192 1056767 1048576 512M c W95 FAT32 (LBA)
{bootfs}
/dev/sdb2 1056768 4190398463 4189341696 2T 83 Linux
{rootfs}
Using "Disks" amplio "rootfs" fins als 2 TB
Device Boot Start End Sectors Size Id Type
/dev/sdb1 8192 1056767 1048576 512M c W95 FAT32 (LBA) {bootfs}
/dev/sdb2 1056768 4190398463 4189341696 2T 83 Linux {rootfs}
Freezes at "Welcome to the Raspberry Pi Desktop. Powered by Raspberry Pi OS (64-bit). Release 5.2 - March 2024."
Imager : Raspberry Pi OS (32-bit) has been written to Generic Mass-Storage (bootfs, rootfs)
Freezes at "Welcome to the Raspberry Pi Desktop. Powered by Raspberry Pi OS (32-bit). Release 5.2 - March 2024."
h2testw (large) :
Try
man badblocks
ebas@minie:~/logs$ sudo badblocks -v -s /dev/sdb > badblocks.txt
Checking blocks 0 to 2097151999
Crear filesystem a ma :
sebas@minie:~$ sudo fdisk /dev/sdb
Welcome to fdisk (util-linux 2.37.2).
Command (m for help): p
Disk /dev/sdb: 1,95 TiB, 2147483648000 bytes, 4194304000 sectors
Disk model: Mass-Storage
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x75d6d1b4
Device Boot Start End Sectors Size Id Type
/dev/sdb1 2048 1026047 1024000 500M c W95 FAT32 (LBA) {bootfs}
/dev/sdb2 1026048 4194303999 4193277952 2T 5 Extended
/dev/sdb5 1028096 68136959 67108864 32G 83 Linux {rootfs}
Conclusio : no podem fer servir eixes SD
R3 new SD - Nov 2024 i Desembre 2024
Mentre som fora, se'n va la llum (25 i 27 Oct 2024) i R3 apareix amb "rainbow boot screen" {gracies, Albert}
See R4 new SD 2022 ...
Provar de posar
- boot_delay=1 to the config.txt file
- connect serial console - freebsd forum
0 : comprem una SD de 64 GB, la posem al adaptador i el conectem a minie :
Dec 10 13:19:26 minie kernel: [12090.004078] usb 1-2: new full-speed USB device number 4 using xhci_hcd
Dec 10 13:19:26 minie kernel: [12090.125214] usb 1-2: device descriptor read/64, error -71
Dec 10 13:19:26 minie kernel: [12090.669373] usb 1-2: new high-speed USB device number 5 using xhci_hcd
Dec 10 13:19:27 minie kernel: [12090.796801] usb 1-2: New USB device found, idVendor=1908, idProduct=0226, bcdDevice= 1.11
Dec 10 13:19:27 minie kernel: [12090.796816] usb 1-2: New USB device strings: Mfr=0, Product=0, SerialNumber=0
Dec 10 13:19:27 minie mtp-probe: checking bus 1, device 5: "/sys/devices/pci0000:00/0000:00:08.1/0000:05:00.3/usb1/1-2"
Dec 10 13:19:27 minie mtp-probe: bus: 1, device: 5 was not an MTP device
Dec 10 13:19:27 minie kernel: [12090.814610] usb-storage 1-2:1.0: USB Mass Storage device detected
Dec 10 13:19:27 minie kernel: [12090.814730] scsi host1: usb-storage 1-2:1.0
Dec 10 13:19:27 minie kernel: [12090.814811] usbcore: registered new interface driver usb-storage
Dec 10 13:19:27 minie kernel: [12090.816382] usbcore: registered new interface driver uas
Dec 10 13:19:27 minie mtp-probe: checking bus 1, device 5: "/sys/devices/pci0000:00/0000:00:08.1/0000:05:00.3/usb1/1-2"
Dec 10 13:19:27 minie mtp-probe: bus: 1, device: 5 was not an MTP device
Dec 10 13:19:28 minie kernel: [12091.834010] scsi 1:0:0:0: Direct-Access Generic Mass-Storage 1.11 PQ: 0 ANSI: 2
Dec 10 13:19:28 minie kernel: [12091.834730] sd 1:0:0:0: Attached scsi generic sg1 type 0
Dec 10 13:19:28 minie kernel: [12092.601222] sd 1:0:0:0: [sdb] 124735488 512-byte logical blocks: (63.9 GB/59.5 GiB)
Dec 10 13:19:28 minie kernel: [12092.601572] sd 1:0:0:0: [sdb] Write Protect is off
Dec 10 13:19:28 minie kernel: [12092.601576] sd 1:0:0:0: [sdb] Mode Sense: 03 00 00 00
Dec 10 13:19:28 minie kernel: [12092.601943] sd 1:0:0:0: [sdb] No Caching mode page found
Dec 10 13:19:28 minie kernel: [12092.601946] sd 1:0:0:0: [sdb] Assuming drive cache: write through
Dec 10 13:19:28 minie kernel: [12092.607023] sdb: sdb1
Dec 10 13:19:28 minie kernel: [12092.607268] sd 1:0:0:0: [sdb] Attached SCSI removable disk
Dec 10 13:19:29 minie udisksd[805]: Mounted /dev/sdb1 at /media/sebas/3364-3038 on behalf of uid 1000
1er : mirem el contingut
sebas@minie:~$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
sda 8:0 0 232,9G 0 disk
└─sda1 8:1 0 232,9G 0 part
sdb 8:16 1 59,5G 0 disk
└─sdb1 8:17 1 59,5G 0 part /media/sebas/3364-3038
nvme0n1 259:0 0 931,5G 0 disk
├─nvme0n1p1 259:1 0 100M 0 part /boot/efi
├─nvme0n1p2 259:2 0 16M 0 part
├─nvme0n1p3 259:3 0 497,9G 0 part
├─nvme0n1p4 259:4 0 1000M 0 part
└─nvme0n1p5 259:5 0 432,6G 0 part /
2on : mirem quin RPI hi ha al Minie :
sebas@minie:~$ dpkg-query -l rpi-imager
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name Version Architecture Description
+++-==============-============-============-=================================
ii rpi-imager 1.8.5 amd64 Raspberry Pi imaging utility
3er : engeguem rpi-imager buscant "rpi" al Menu
Imager 1.8.5 :
device := Raspberry Pi 3 (models B, A+, B+)
operating system := Raspberry Pi OS (32 bit) # el 64-bit obre un prompt pelat en 15 minuts
storage := Generic Mass Storage - 62,6 GB {63,9}
Apply SO customization settings ? (hostname, usr/pwd, Wifi SSID/pwd, enable SSH)
Raspberry Pi OS (32-bit) has been written to "Generic Mass-Storage".
You can now remove the SD from the reader.
Es veu :
sebas@minie:~$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINTS
sda 8:0 0 232,9G 0 disk
└─sda1 8:1 0 232,9G 0 part
sdb 8:16 1 0B 0 disk
<move SD to R3> :
Welcome to the Raspberry Pi Desktop
Powered by Raspberry Pi OS (32-bit)
Release 5.4, October 2024 {5.5, November 2024}
La imatge surt desplaçada cap dalt, pero podem obrir un Terminal per veure la IP {192.168.1.141} i aixi poder conectar-hi en remot.
La versio de Raspbian que tenim es :
pi@r3-64gb:~ $ cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 12 (bookworm)"
NAME="Raspbian GNU/Linux"
VERSION_ID="12"
VERSION="12 (bookworm)"
VERSION_CODENAME=bookworm
ID=raspbian
ID_LIKE=debian
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"
Les versions de Debian son :
8 = Jessie
9 = Stretch
10 = Buster
11 = Bullseye
12 = Bookworm - 31 de Agost de 2024 -
Debian
reconfiguracio del R3 i re-instalacio de software
D'entrada, baixem "odinpic_odin.tar" des "sveta@aol.com"
pi@r3-64gb:~ $ sudo apt update
45 packages can be upgraded. Run 'apt list --upgradable' to see them.
pi@r3-64gb:~ $ apt list --upgradable {llista llarga}
pi@r3-64gb:~ $ sudo apt-get dist-upgrade {triga una bona estona}
Calculating upgrade... Done
The following package was automatically installed and is no longer required:
xinput
Use 'sudo apt autoremove' to remove it.
The following packages will be REMOVED:
lxinput
apt-listchanges: Can't set locale; make sure $LC_* and $LANG are correct!
Reading changelogs... Done
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = (unset),
LC_ALL = (unset),
LC_MONETARY = "es_ES.UTF-8",
LC_ADDRESS = "es_ES.UTF-8",
LC_TELEPHONE = "es_ES.UTF-8",
LC_NAME = "es_ES.UTF-8",
LC_MEASUREMENT = "es_ES.UTF-8",
LC_IDENTIFICATION = "es_ES.UTF-8",
LC_NUMERIC = "es_ES.UTF-8",
LC_PAPER = "es_ES.UTF-8",
LANG = "en_GB.UTF-8"
are supported and installed on your system.
perl: warning: Falling back to a fallback locale ("en_GB.UTF-8").
locale: Cannot set LC_ALL to default locale: No such file or directory
Configuration file '/etc/xdg/labwc/environment'
==> Modified (by you or by a script) since installation.
==> Package distributor has shipped an updated version.
What would you like to do about it ? Your options are:
Y or I : install the package maintainer's version
N or O : keep your currently-installed version
D : show the differences between the versions
Z : start a shell to examine the situation
The default action is to keep your current version.
*** environment (Y/I/N/O/D/Z) [default=N] ? y
Error: Timeout was reached
Try to fix LC_ALL :
pi@r3-64gb:~ $ sudo raspi-config
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = (unset),
LC_ALL = (unset),
LC_MONETARY = "es_ES.UTF-8",
LC_ADDRESS = "es_ES.UTF-8",
LC_TELEPHONE = "es_ES.UTF-8",
LC_NAME = "es_ES.UTF-8",
LC_MEASUREMENT = "es_ES.UTF-8",
LC_IDENTIFICATION = "es_ES.UTF-8",
LC_NUMERIC = "es_ES.UTF-8",
LC_PAPER = "es_ES.UTF-8",
LANG = "en_GB.UTF-8"
are supported and installed on your system.
perl: warning: Falling back to a fallback locale ("en_GB.UTF-8").
locale: Cannot set LC_ALL to default locale: No such file or directory
/usr/bin/locale: Cannot set LC_ALL to default locale: No such file or directory
Generating locales (this might take a while)...
en_GB.UTF-8... done
es_ES.UTF-8... done
Generation complete.
Ara no tinc errors (he marcat "en_GB.UTF-8" i tambe "es_ES.UTF-8")
pi@r3-64gb:~ $ sudo apt-get dist-upgrade
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Calculating upgrade... Done
The following package was automatically installed and is no longer required:
xinput
Use 'sudo apt autoremove' to remove it.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
R3 - install logram
pi@r3-64gb:~ $ sudo apt install log2ram
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
E: Unable to locate package log2ram
echo "deb [signed-by=/usr/share/keyrings/azlux-archive-keyring.gpg] \
http://packages.azlux.fr/debian/ bullseye main" | sudo tee /etc/apt/sources.list.d/azlux.list
deb [signed-by=/usr/share/keyrings/azlux-archive-keyring.gpg] http://packages.azlux.fr/debian/ bullseye main
sudo wget -O /usr/share/keyrings/azlux-archive-keyring.gpg https://azlux.fr/repo.gpg
pi@r3-64gb:~ $ sudo apt update
Get:1 http://packages.azlux.fr/debian bullseye InRelease [3997 B]
Hit:2 http://archive.raspberrypi.com/debian bookworm InRelease
Hit:3 http://raspbian.raspberrypi.com/raspbian bookworm InRelease
Get:4 http://packages.azlux.fr/debian bullseye/main arm64 Packages [4249 B]
Get:5 http://packages.azlux.fr/debian bullseye/main armhf Packages [4554 B]
Fetched 12.8 kB in 2s (7500 B/s)
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
All packages are up to date.
W: http://raspbian.raspberrypi.com/raspbian/dists/bookworm/InRelease:
Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg),
see the DEPRECATION section in apt-key(8) for details.
pi@r3-64gb:~ $ sudo apt install log2ram
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following NEW packages will be installed:
log2ram
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 5368 B of archives.
After this operation, 0 B of additional disk space will be used.
Get:1 http://packages.azlux.fr/debian bullseye/main armhf log2ram all 1.7.2 [5368 B]
Fetched 5368 B in 0s (42.3 kB/s)
(Reading database ... 136298 files and directories currently installed.)
Preparing to unpack .../archives/log2ram_1.7.2_all.deb ...
Unpacking log2ram (1.7.2) ...
Setting up log2ram (1.7.2) ...
Created symlink /etc/systemd/system/sysinit.target.wants/log2ram.service → /etc/systemd/system/log2ram.service.
Created symlink /etc/systemd/system/timers.target.wants/log2ram-daily.timer → /etc/systemd/system/log2ram-daily.timer.
##### Reboot to activate log2ram #####
##### edit /etc/log2ram.conf to configure options ####
pi@r3-64gb:~ $ sudo vi /etc/log2ram.conf
# Specify the amount of RAM reserved for storing logs. This setting determines the maximum size of the RAM folder.
# Ensure 'SIZE=' is set larger than the current size of your /var/log directory to prevent startup failures.
# Also, configure logrotate to manage log growth and prevent the /var/log directory from exceeding this reserved size.
SIZE=128M
# By default, if there is insufficient RAM space, a system notification email is sent.
# Set this to 'false' to disable email notifications. (The error will still be logged locally).
NOTIFICATION=true
# Specify the command for sending error notifications.
# By default, it uses the `mail` command to send an email, with the message body provided via stdin.
# You can replace this with any command (such as 'shoutrrr') or a custom script for handling notifications.
NOTIFICATION_COMMAND=mutt -s "Log2Ram Error on $HOSTNAME"
# Specify the directories to be stored in RAM. List each directory using its absolute path, e.g., `/path/folder`.
# Corresponding directories on the HDD, named `/path/hdd.folder`, will be automatically created for each listed path.
# Separate multiple paths with a semicolon `;` and do not include a trailing slash at the end of the paths.
# Example: PATH_DISK="/var/log;/home/test/FolderInRam"
PATH_DISK="/var/log;/home/pi/logs"
R3 - install and configure mutt
pi@r3-64gb:~ $ sudo apt-get install mutt
pi@r3-64gb:~ $ mkdir -p ~/.mutt/cache/headers
pi@r3-64gb:~ $ mkdir ~/.mutt/cache/bodies
pi@r3-64gb:~ $ touch ~/.mutt/certificates
Afegim al final del fitxer de configuracio del mutt :
pi@r3-64gb:~ $ cat /etc/Muttrc
# +++ +++ +++ sebas, 20241108, new R3
# 20241108 - new R3
set from = "adb30@tinet.cat"
set realname = "Amics del Basket 30@odin"
set imap_user = "adb30@tinet.cat"
set imap_pass = "clau"
set smtp_url = "smtps://adb30@smtp.tinet.cat:465/"
set smtp_pass = "clau"
set folder = "imaps://imap.tinet.cat:993"
set spoolfile = "+INBOX"
set header_cache = "/home/sebas/.mutt/cache/headers"
set message_cachedir = "/home/sebas/.mutt/cache/bodies"
set certificate_file = "/home/sebas/.mutt/certificates"
set ssl_verify_host = no
set ssl_verify_dates = no
set mail_check = 120
set move = no
set imap_keepalive = 900
set sort = threads
set editor = "vi"
# +++ sebas - no posar lo q enviem al fitxer "sent"
set copy = no
Verifiquem que funciona :
echo "my BODY" | mutt -d 5 -s "my SUBJECT" -- mydestinationemail@gmail.com # OK !
R3 - fixed IP for wlan0
Fem servir nmcli at
StackExchange : nmtui
Display our names :
pi@r3-64gb:~ $ sudo nmcli c show
NAME UUID TYPE DEVICE
preconfigured 7d5ad85d-2b82-422d-b776-289e054fd7d8 wifi wlan0
lo 6ae5b9a3-f278-487e-97c8-1ba125e50321 loopback lo
Wired connection 1 ceea885b-72f2-3414-b18e-50bfcacd9c09 ethernet --
Set static IP :
sudo nmcli con mod 'preconfigured' ipv4.addresses 192.168.1.123/24 ipv4.method manual
sudo nmcli con mod 'preconfigured' ipv4.gateway 192.168.1.1
sudo nmcli con mod 'preconfigured' ipv4.dns "8.8.8.8"
sudo nmcli con down 'preconfigured' && sudo nmcli con up 'preconfigured'
forums raspberry
Amb la eina grafica :
pi@r3-64gb:~ $ sudo nmtui
┌─┤ NetworkManager TUI ├──┐
│ │
│ Please select an option │
│ │
│ Edit a connection │
│ Activate a connection │
│ Set system hostname │
│ │
│ Quit │
│ │
│ <OK> │
R3 - crontab
Tenim aquestes feines programades :
# m h dom mon dow command
*/5 * * * * /home/pi/duckdns/duck.sh >/dev/null 2>&1
4 2 * * * /home/pi/python/telegram/missatge_a_telegram.sh kron
33 5 * * * cd /home/pi/eines/backup && /home/pi/eines/backup/fer_backup.sh
25,55 * * * * cd /home/pi/python/tinet && /home/pi/python/tinet/enviar_html_a_tinet.py &>> /home/pi/logs/enviar_html_a_tinet.log
Create some dirs and files :
mkdir /home/pi/logs/
touch /home/pi/logs/engegades.log
touch /home/pi/logs/rc.local.log
Per veure els errors del cron ens cal la comanda "mail" :
pi@r3-64gb:~ $ sudo apt-get install mailutils
pi@r3-64gb:~ $ mail -s "Test Subject" pi@localhost < /dev/null
R3 - startup and services
At R3 restart we do :
- afegir una linia a "/logs/engegades.log"
- posar una marca temporal a "/logs/last_boot_time.log"
- enviar un missatge al bot de TG
Fem servir /usr/local/bin/odin_restart des /etc/rc.local
pi@r3-64gb:/etc $ sudo chmod 744 rc.local
pi@r3-64gb:~ $ sudo systemctl status rc-local.service
● rc-local.service - /etc/rc.local Compatibility
Loaded: loaded (/lib/systemd/system/rc-local.service; enabled-runtime; preset: enabled)
Drop-In: /usr/lib/systemd/system/rc-local.service.d
└─debian.conf
Active: active (exited) since Tue 2024-12-10 21:35:36 CET; 4min 8s ago
Docs: man:systemd-rc-local-generator(8)
Process: 1001 ExecStart=/etc/rc.local start (code=exited, status=0/SUCCESS)
CPU: 1.528s
Dec 10 21:35:36 r3-64gb systemd[1]: Starting rc-local.service - /etc/rc.local Compatibility...
Dec 10 21:35:36 r3-64gb systemd[1]: Started rc-local.service - /etc/rc.local Compatibility.
2024.12.09 : fsck on Raspbian SD
Se'n va la llum i R3 no engega.
"disks" de minie diu "filesystem needs repairing"
sebas@minie:~$ sudo fsck /dev/sdb
fsck from util-linux 2.37.2
e2fsck 1.46.5 (30-Dec-2021)
ext2fs_open2: Bad magic number in super-block
fsck.ext2: Superblock invalid, trying backup blocks...
fsck.ext2: Bad magic number in super-block while trying to open /dev/sdb
The superblock could not be read or does not describe a valid ext2/ext3/ext4 filesystem.
If the device is valid and it really contains an ext2/ext3/ext4 filesystem
(and not swap or ufs or something else),
then the superblock is corrupt, and you might try running e2fsck with an alternate superblock:
e2fsck -b 8193 <device>
or
e2fsck -b 32768 <device>
Found a dos partition table in /dev/sdb
Crec que no es pot arreglar.
Proves de funcionament del "odin" o "R3"
- fer foto des la webcam amb "python /home/pi/semafor/4_foto_verbose.py"
- veure la imatge continua de la webcam amb "python /home/pi/semafor/9_webcam.py" - compte : la sortida es per HDMI,
excepte si amb "DISPLAY" la enviem al Xming del W500
- enviar email (verify "telnet gmail-smtp-in.l.google.com smtp" works first) amb /home/pi/sendemail/snd_1.sh
- enviar missatge amb whatsapp - no tf number
Audio, sound
The Raspberry Pi has two audio output modes: HDMI and headphone jack.
You can switch between these modes at any time.
The HDMI audio is digital and multiplexed in with digital video.
The analogue audio output on the RPI's 3.5 mm TRRS jack is line level and will not drive speakers directly.
Power amplification is necessary.
What about USB speakers ?
Esquemes
Soft and config
To not to use "sudo" all the time, lets do :
$ sudo usermod -a -G audio sag
$ sudo usermod -a -G video sag
Lets start with :
$ sudo amixer cset numid=3 0 # output set to "Automatic"
$ sudo amixer cset numid=3 1 # output set to analogue (headphone jack)
$ sudo amixer cset numid=3 2 # output set to HDMI
sag@odin:~/sounds $ sudo amixer cset numid=3 1
PuTTY X11 proxy: wrong authentication protocol attemptedxcb_connection_has_error() returned true
numid=3,iface=MIXER,name='PCM Playback Route'
; type=INTEGER,access=rw------,values=1,min=0,max=2,step=0
: values=1
sag@odin:~/sounds $ sudo amixer
PuTTY X11 proxy: MIT-MAGIC-COOKIE-1 data did not match xcb_connection_has_error() returned true
Simple mixer control 'PCM',0
Capabilities: pvolume pvolume-joined pswitch pswitch-joined
Playback channels: Mono
Limits: Playback -10239 - 400
Mono: Playback -1969 [78%] [-19.69dB] [on]
Audio Config, also
here
Somehow related to values in
/boot/config.txt file :
hdmi_drive=1 # ?
hdmi_drive=2 # force HDMI
Les meves proves al "odin" :
sag@odin:~ $ aplay -l
aplay: device_list:268: no soundcards found...
sag@odin:~ $ sudo aplay -l (List all soundcards and digital audio devices)
**** List of PLAYBACK Hardware Devices ****
PuTTY X11 proxy: wrong authentication protocol attemptedxcb_connection_has_error() returned true
card 0: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA]
Subdevices: 8/8
Subdevice #0: subdevice #0
Subdevice #1: subdevice #1
Subdevice #2: subdevice #2
Subdevice #3: subdevice #3
Subdevice #4: subdevice #4
Subdevice #5: subdevice #5
Subdevice #6: subdevice #6
Subdevice #7: subdevice #7
card 0: ALSA [bcm2835 ALSA], device 1: bcm2835 ALSA [bcm2835 IEC958/HDMI]
Subdevices: 1/1
Subdevice #0: subdevice #0
sag@odin:~/sounds $ sudo aplay -L (List all PCMs defined)
PuTTY X11 proxy: MIT-MAGIC-COOKIE-1 data did not match xcb_connection_has_error() returned true
PuTTY X11 proxy: MIT-MAGIC-COOKIE-1 data did not match xcb_connection_has_error() returned true
null
Discard all samples (playback) or generate zero samples (capture)
pulse
PulseAudio Sound Server
default:CARD=ALSA
bcm2835 ALSA, bcm2835 ALSA
Default Audio Device
sysdefault:CARD=ALSA
bcm2835 ALSA, bcm2835 ALSA
Default Audio Device
dmix:CARD=ALSA,DEV=0
bcm2835 ALSA, bcm2835 ALSA
Direct sample mixing device
dmix:CARD=ALSA,DEV=1
bcm2835 ALSA, bcm2835 IEC958/HDMI
Direct sample mixing device
dsnoop:CARD=ALSA,DEV=0
bcm2835 ALSA, bcm2835 ALSA
Direct sample snooping device
dsnoop:CARD=ALSA,DEV=1
bcm2835 ALSA, bcm2835 IEC958/HDMI
Direct sample snooping device
hw:CARD=ALSA,DEV=0
bcm2835 ALSA, bcm2835 ALSA
Direct hardware device without any conversions
hw:CARD=ALSA,DEV=1
bcm2835 ALSA, bcm2835 IEC958/HDMI
Direct hardware device without any conversions
plughw:CARD=ALSA,DEV=0
bcm2835 ALSA, bcm2835 ALSA
Hardware device with all software conversions
plughw:CARD=ALSA,DEV=1
bcm2835 ALSA, bcm2835 IEC958/HDMI
Hardware device with all software conversions
sag@odin:/etc $ sudo modprobe snd_bcm2835
sag@odin:/etc $ sudo lsmod | grep snd_bcm2835
snd_bcm2835 24427 1
snd_pcm 98501 2 snd_usb_audio,snd_bcm2835
snd 70032 10 snd_hwdep,snd_usb_audio,snd_timer,snd_rawmidi,snd_usbmidi_lib,snd_seq_device,snd_bcm2835,snd_pcm
sag@odin:/boot $ cat /boot/config.txt | grep audio
# uncomment to force a HDMI mode rather than DVI. This can make audio work in
# Enable audio (loads snd_bcm2835)
dtparam=audio=on
sag@odin:/boot $ cat /proc/asound/cards
0 [ALSA ]: bcm2835 - bcm2835 ALSA
bcm2835 ALSA
1 [U0x46d0x8da ]: USB-Audio - USB Device 0x46d:0x8da
USB Device 0x46d:0x8da at usb-3f980000.usb-1.3, full speed
$ omxplayer /home/sag/sounds/laser_cannon.wav # funciona amb HDMI
homepage
root@odin:/opt/vc/src/hello_pi/hello_audio# cd /opt/vc/src/hello_pi/libs/ilclient
root@odin:/opt/vc/src/hello_pi/libs/ilclient# make
root@odin:/opt/vc/src/hello_pi/hello_audio# make
System Tool :
root@odin:/opt/vc/src/hello_pi/hello_audio# ./hello_audio.bin # test analogue output *** funciona 20190415 ***
Outputting audio to analogue (till CTRL-C)
root@odin:/opt/vc/src/hello_pi/hello_audio# ./hello_audio.bin 1 # test output to HDMI *** funciona 20190415 ***
Outputting audio to hdmi (till CTRL-C)
I ask the
experts ... but ...
Tried :
sag@odin:~ $ sudo cp .Xauthority /root/.
It removes the "X11 proxy" error, but "xcb" persists
Things can get worse :
sag@odin:~/sounds $ sudo arecord -l
**** List of CAPTURE Hardware Devices ****
PuTTY X11 proxy: MIT-MAGIC-COOKIE-1 data did not matchxcb_connection_has_error() returned true
card 1: U0x46d0x8da [USB Device 0x46d:0x8da], device 0: USB Audio [USB Audio]
Subdevices: 1/1
Subdevice #0: subdevice #0
sag@odin:~/sounds $ xauth list
odin/unix:12 MIT-MAGIC-COOKIE-1 249b212f335f418d67848229efa765e6
odin/unix:10 MIT-MAGIC-COOKIE-1 77a24968440342ff28b90e40223da6d0
odin/unix:11 MIT-MAGIC-COOKIE-1 4ae40f594787805dacd9fd99d61a7b0a
sag@odin:~/sounds $ xauth
Using authority file /home/sag/.Xauthority
xauth> list
odin/unix:12 MIT-MAGIC-COOKIE-1 249b212f335f418d67848229efa765e6
odin/unix:10 MIT-MAGIC-COOKIE-1 77a24968440342ff28b90e40223da6d0
odin/unix:11 MIT-MAGIC-COOKIE-1 4ae40f594787805dacd9fd99d61a7b0a
xauth> remove unix:12
1 entries removed
xauth> exit
Writing authority file /home/sag/.Xauthority
Anem resolvent-ho :
root@odin:/home/sag/sounds# aplay buzzer.wav
xcb_connection_has_error() returned true
Playing WAVE 'buzzer.wav' : Signed 16 bit Little Endian, Rate 44100 Hz, Stereo
sag@odin:~/sounds $ sudo aplay buzzer.wav
[sudo] password for sag:
PuTTY X11 proxy: MIT-MAGIC-COOKIE-1 data did not match xcb_connection_has_error() returned true
Playing WAVE 'buzzer.wav' : Signed 16 bit Little Endian, Rate 44100 Hz, Stereo
Es a dir, per a que vagi be hem fet "sudo su -", ens hem posat com "root"
Per a veure el volum des la command line, fem
sag@odin:~/sounds $ sudo alsamixer
┌──────────────────────────────────────────────────────── AlsaMixer v1.0.28 ────────────────────────────────────────────────────────┐
│ Card: bcm2835 ALSA F1: Help │
│ Chip: Broadcom Mixer F2: System information │
│ View: F3:[Playback] F4: Capture F5: All F6: Select sound card │
│ Item: PCM [dB gain: -20.36] Esc: Exit
Aqui es veu el nivell del volum i es pot modificar amb "arrow up/down"
mpg321
description,
install : "apt-get install mpg321"
sox
sox homepage,
intro
We do :
sag@odin:~/sounds $ sudo apt-get install sox
[sudo] password for sag:
Reading package lists... Done
. . .
sag@odin:~/sounds $ sudo apt-get install libsox-fmt-mp3
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
libtwolame0
Get
soundplayer.py,
"unzip python-sound.zip" and run
root@odin:/home/sag/sounds# cat sox_1.py
import time
from soundplayer import SoundPlayer
# Use device with ID 1 (mostly USB audio adapter)
p = SoundPlayer("/home/sag/sounds/laser_cannon.wav", 1)
print "play for 10 s with volume 0.5"
p.play(0.5) # non-blocking, volume = 0.5
print "isPlaying:", p.isPlaying()
time.sleep(10)
print "pause for 5 s"
p.pause()
print "isPlaying:", p.isPlaying()
time.sleep(5)
print "resume for 10 s"
p.resume()
time.sleep(10)
print "stop"
p.stop()
print "isPlaying:", p.isPlaying()
print "done"
root@odin:/home/sag/sounds#
Nothing comes up !
Minor fixes
Noise in syslog.conf - dhcpcd
In /var/log/syslog I fond lots of :
Sep 5 20:11:29 odin dhcpcd[513]: wlan0: Router Advertisement from fe80::e241:36ff:febc:bcd1
Sep 5 20:11:39 odin dhcpcd[513]: wlan0: Router Advertisement from fe80::e241:36ff:febc:bcd1
I edit dhcp client configuration :
sag@odin:/etc $ sudo vi /etc/dhcpcd.conf
# the rest of the options are above - SAG, 20190905
ipv4only
noipv6
nodhcp6
And finally :
sag@odin:/etc $ sudo service dhcpcd restart
url
v8 -> v9 -> v10
As Pi0 is "buster", v10, and I need python 3.5 in "odin" for smbus2, I decide a big upgrade.
jessie 2 stretch
again
Check for any system inconsistencies - check for partially installed, missing and obsolete packages: dpkg -C
- $ sudo dpkg --audit
- $ sudo dpkg --get-selections | grep hold
- $ sudo apt-get update ; sovint
- $ sudo apt-get upgrade ; delicat
- $ sudo apt-get dist-upgrade
- # apt-get --simulate upgrade ;
- $ sudo sed -i /deb/s/jessie/stretch/g /etc/apt/sources.list
- $ sudo sed -i /deb/s/jessie/stretch/g /etc/apt/sources.list.d/*.list
- $ grep -lnr jessie /etc/apt ; expect no output
- $ sudo apt-get remove apt-listchanges
- $ sudo apt-get upgrade - 1h
- $ sudo apt-get dist-upgrade - apt-listchanges: Mailing root: apt-listchanges: news for odin
- $ sudo apt-get autoremove
- $ sudo apt-get autoclean
- reboot
- verify : hostnamectl
First try result :
Preconfiguring packages ...
Traceback (most recent call last):
File "/tmp/tmp.foOIAifKir.aptlc/debconf-helper.py", line 6, in
import debconf
ModuleNotFoundError: No module named 'debconf'
apt-listchanges failed to preconfigure, with exit status 1
dpkg: perl-modules: dependency problems, but removing anyway as you requested:
perl depends on perl-modules (>= 5.20.2-3+deb8u12).
libmailtools-perl depends on libnet-perl; however:
Package libnet-perl is not installed.
Package perl-modules which provides libnet-perl is to be removed.
dpkg: libreadline6-dev:armhf: dependency problems, but removing anyway as you requested:
libreadline-dev:armhf depends on libreadline6-dev (= 6.3-8).
dpkg: libopencv-imgproc2.4:armhf: dependency problems, but removing anyway as you requested:
libopencv-highgui2.4:armhf depends on libopencv-imgproc2.4 (= 2.4.9.1+dfsg-1+deb8u2); however:
Package libopencv-imgproc2.4:armhf is to be removed.
dpkg: warning: unable to delete old directory '/etc/xdg/lxsession/LXDE': Directory not empty
dpkg: warning: unable to delete old directory '/etc/xdg/openbox/LXDE': Directory not empty
dpkg: warning: unable to delete old directory '/etc/xdg/lxpanel/profile/LXDE-pi/panels': Directory not empty
dpkg: warning: unable to delete old directory '/etc/xdg/lxpanel/profile/LXDE-pi': Directory not empty
dpkg: warning: unable to delete old directory '/etc/xdg/lxpanel/profile': Directory not empty
Errors were encountered while processing:
apt-listchanges
E: Sub-process /usr/bin/dpkg returned an error code (1)
We try
sag@odin:/usr/lib/python3/dist-packages $ sudo apt-get install --reinstall debconf
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reinstallation of debconf is not possible, it cannot be downloaded.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n]
Setting up apt-listchanges (3.10) ...
Traceback (most recent call last):
File "/tmp/tmp.iNAgX96b5Z.aptlc/debconf-helper.py", line 6, in <module>
import debconf
ModuleNotFoundError: No module named 'debconf'
dpkg: error processing package apt-listchanges (--configure):
subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
apt-listchanges
E: Sub-process /usr/bin/dpkg returned an error code (1)
sudo apt-get -f install debconf
sudo dpkg-reconfigure debconf
sudo dpkg ––configure –a
sag@odin:/tmp $ sudo dpkg -C
The following packages are only half configured, probably due to problems
configuring them the first time. The configuration should be retried using
dpkg --configure <package> or the configure menu option in dselect:
apt-listchanges package change history notification tool
sag@odin:/tmp $ sudo dpkg --configure apt-listchanges
Setting up apt-listchanges (3.10) ...
Traceback (most recent call last):
File "/tmp/tmp.7AMjuAekH2.aptlc/debconf-helper.py", line 6, in <module>
import debconf
ModuleNotFoundError: No module named 'debconf'
dpkg: error processing package apt-listchanges (--configure):
subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
apt-listchanges
sag@odin:/tmp $ sudo apt-cache policy debconf debconf-i18n debconf-utils
debconf:
Installed: 1.5.61
Candidate: 1.5.61
Version table:
*** 1.5.61 100
100 /var/lib/dpkg/status
debconf-i18n:
Installed: 1.5.61
Candidate: 1.5.61
Version table:
*** 1.5.61 100
100 /var/lib/dpkg/status
debconf-utils:
Installed: 1.5.61
Candidate: 1.5.61
Version table:
*** 1.5.61 100
100 /var/lib/dpkg/status
wget http://mirrordirector.raspbian.org/raspbian/pool/main/d/debconf/debconf_1.5.56+deb8u1_all.deb
sudo dpkg -i debconf_1.5.56+deb8u1_all.deb
sag@odin:/tmp $ sudo apt-get remove apt-listchanges
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
debconf-i18n : Depends: debconf (= 1.5.61) but 1.5.56+deb8u1 is to be installed
debconf-utils : Depends: debconf (= 1.5.61) but 1.5.56+deb8u1 is to be installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).
sag@odin:/tmp $ sudo apt --fix-broken install
sag@odin:/tmp $ sudo apt-get remove apt-listchanges
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following package was automatically installed and is no longer required:
python3-apt
Use 'sudo apt autoremove' to remove it.
The following packages will be REMOVED:
apt-listchanges
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 377 kB disk space will be freed.
Do you want to continue? [Y/n]
(Reading database ... 135135 files and directories currently installed.)
Removing apt-listchanges (3.10) ...
Processing triggers for man-db (2.7.6.1-2) ...
sag@odin:/tmp $ sudo dpkg -C
Projectes amb el Raspberry
Amb el Raspberry hem fer projectes macos :
- LED on/off from remote browser
- take a picture using web camera and detect contour
- take one pic every 5 seconds and place it into a web page
- mesura de soroll a Roda
Projectes pel futur
Amb el Raspberry volem fer altres projectes :
- Alexa home assistant
- AWS "device"
- Magic Mirror : okupatic
LED amb python i node
Descripció de un
LED aillat amb un transistor.
Codi exemple - 1 LED manegat per python : GPIO-026
Tinc 3 LEDS manegats per un transistor SC107, Rc 1k5, Rb 100k (Ic 2 mA) :
- un de verd al pin 18, BCM24, cable blanc
- un de groc al pin 15, BCM22, cable gris
- un de vermell al pin 16, BCM23, cable negre
tres LEDs amb python
\\albert\python\RasPi> type mou_leds.py
#!/usr/bin/python
# el codi estira de numeros BCM, vol dir que
# el "yellow" correspon al pin BCM22, pin numero 15, cable gris
# el "red" correspon al pin BCM23, pin numero 16, cable negre
# el "green" correspon al pin BCM24, pin numero 18, cable blanc
import RPi.GPIO as GPIO
import time
import atexit
class Pins():
byname = { 'yellow': 22,
'red' : 23,
'green' : 24 }
def __init__(self):
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
for led in self.byname.itervalues():
GPIO.setup(led, GPIO.OUT)
def on(self, pin):
GPIO.output(pin, True)
def off(self, pin):
GPIO.output(pin, False)
def finikito_method():
print( "From FINIKITO method - apaguem tots els LEDs" )
for led in leds.byname:
print time.strftime( "%Y/%m/%d %H:%M:%S" ) + ' - apaguem led {}'.format(led)
leds.off( leds.byname[led] )
atexit.register(finikito_method)
if __name__ == '__main__':
leds = Pins()
while True:
try:
for led in leds.byname:
print time.strftime( "%Y/%m/%d %H:%M:%S" ) + ' - switching led {}'.format(led)
leds.on( leds.byname[led] )
time.sleep(1)
leds.off( leds.byname[led] )
except KeyboardInterrupt:
print "Teclat"
break # get out of the "while true" loop
un LED amb node
pi@raspberrypi-llovet:~/semafor $ cat app.js
// http://www.instructables.com/id/Javascripting-Your-RaspberryPi/step5/Time-for-some-GPIO/
// Manages 4 messages from browser :
// http://192.168.1.123:3000 - display welcome message
// http://192.168.1.123:3000/light - display led status
// http://192.168.1.123:3000/light/on - turn led on
// http://192.168.1.123:3000/light/off - turn led off
// NODEJS works in BOARD numbering mode.
// So, writing to pin "18" shall go to physical pin 18, also called BCM24, wired to my LED color GREEN.
var express = require('express');
var app = express();
var gpio = require('rpi-gpio') ; // https://www.npmjs.com/package/rpi-gpio
gpio.setup( 18, gpio.DIR_OUT, off ) ;
function on() {
gpio.write( 18, true, function(err) {
if (err) throw err;
console.log( 'Written ON to pin 18.' );
});
}
function off() {
gpio.write( 18, false, function(err) {
if (err) throw err;
console.log( 'Written OFF to pin 18.' );
});
}
var state = 'off';
app.get( '/', function (req, res) { res.send( 'Hello World!' ); });
app.get( '/light', function (req, res) { res.send( 'The light is currently ' + state + '.' ); });
app.get( '/light/on', function (req, res) { res.send( 'Turning the light on...' ); state = 'on'; on(); });
app.get( '/light/off', function (req, res) { res.send( 'Turning the light off...' ); state = 'off'; off(); });
var server = app.listen( 3000, "192.168.1.123", function () {
var host = server.address().address;
var port = server.address().port;
console.log( '>>> App listening at http://%s:%s', host, port );
});
una bombeta amb node
Cap diferencia amb l'anterior : Ic = 4,8 v / 0,3k = 16 mA
Per manegar tots els pins del GPIO des una web, fem servir aquest
projecte de git
Semàfor
Tenim 3 bombetes de 60 W de AC.
Les volem manegar amb un
Raspberry PI 3 model B.
Cal un
SSR,
as
Crydom D2W203F (14 usd)
or
Crydom CX240D5
(11 € at
Diotronic, 20160615 ; 21 € at
Amazon, 20181102) ;
PDF
O be un
Relay for Raspberry Pi or Arduino 1-Channel 5V Relay Module 250V/10A - 8 USD !
El projecte final es troba al
git
Hardware del semàfor
El pin del Raspberry manegarà la base de un transistor, al colector del qual hi haurà un SSR.
No hi ha resistencia sèrie.
Com que la impedància del SSR és de 0,3k, hi baixaràn (5v - 0,2v) / 0,3k = 4,8/0,3 = 16 mA
Nominal Input Impedance = 300 Ohm, see here
Typical Input Current = 15 mA
Tensio en bornes de control : 15 mA * 0,3 K = 4,5 v
Cablejat
Cables que surten del GPIO del Raspberry cap a la breadboard/protoboard :
- pin 2 : +5v
- pin 9 : ground
- pin 15 : yellow
- pin 16 : red
- pin 18 : green
Software
Switch a light on/off
using your smartphone,
using node.js ! {help.privateeyepi@gmail.com}
- sudo apt-get update {sempre}
- sudo apt-get upgrade {delicat, no fer}
- sudo apt-get install npm
pi@raspberrypi-llovet:~ $ npm -v
1.4.21
- npm install connect
pi@raspberrypi-llovet:~/semafor $ npm install connect
connect@3.4.1 node_modules/connect
âââ utils-merge@1.0.0
âââ parseurl@1.3.1
âââ debug@2.2.0 (ms@0.7.1)
âââ finalhandler@0.4.1 (escape-html@1.0.3, unpipe@1.0.0, on-finished@2.3.0)
- npm install serve-static
pi@raspberrypi-llovet:~/semafor $ npm install serve-static
serve-static@1.11.1 node_modules/serve-static
âââ escape-html@1.0.3
âââ parseurl@1.3.1
âââ encodeurl@1.0.1
âââ send@0.14.1 (destroy@1.0.4, fresh@0.3.0, ms@0.7.1, range-parser@1.2.0, etag@1.7.0, statuses@1.3.0,
debug@2.2.0, depd@1.1.0, mime@1.3.4, on-finished@2.3.0, http-errors@1.5.0)
pi@raspberrypi-llovet:~/semafor $
- npm install serialport - Error, but project does
exist
\
> serialport@3.1.2 install /home/pi/semafor/node_modules/serialport
> node-pre-gyp install --fallback-to-build
node-pre-gyp ERR! Tried to download: https://github.com/voodootikigod/node-serialport/releases/download/3.1.2/serialport-v3.1.2-node-v11-linux-arm.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for serialport@3.1.2 and node@0.10.29 (node-v11 ABI) (falling back to source compile with node-gyp)
make: Entering directory '/home/pi/semafor/node_modules/serialport/build'
CXX(target) Release/obj.target/serialport/src/serialport.o
In file included from ../src/./serialport.h:7:0,
from ../src/serialport.cpp:1:
../node_modules/nan/nan.h:324:47: error: âREPLACE_INVALID_UTF8â is not a member of âv8::Stringâ
static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8;
Fixed when updating "node" to version "5.11.1"
- npm install rpi-gpio - read rpi-gpio
pi@raspberrypi-llovet:~/semafor $ npm install rpi-gpio
normalizeTree â
normalizeTree â fetchName â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
normalizeTree â 200 â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
loadRequestedDeps â fetch â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
loadRequestedDeps â fetch â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
loadRequestedDeps â cache â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
fetchMetadata â 200 â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
fetchMetadata â network â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
fetchMetadata â afterAdd â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
extract:rpi-gpio â gunzTa â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
extract:debug â gentlyRm â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
preinstall:rpi-gpio â lif â â¢âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ
> epoll@0.1.19 install /home/pi/semafor/node_modules/epoll
> node-gyp rebuild
make: Entering directory '/home/pi/semafor/node_modules/epoll/build'
CXX(target) Release/obj.target/epoll/src/epoll.o
SOLINK_MODULE(target) Release/obj.target/epoll.node
COPY Release/epoll.node
make: Leaving directory '/home/pi/semafor/node_modules/epoll/build'
/home/pi/semafor
ââ⬠rpi-gpio@0.7.0
âââ async@1.5.2
ââ⬠debug@2.2.0
â âââ ms@0.7.1
ââ⬠epoll@0.1.19
âââ bindings@1.2.1
âââ nan@2.3.5
npm WARN enoent ENOENT: no such file or directory, open '/home/pi/semafor/package.json'
npm WARN semafor No description
npm WARN semafor No repository field.
npm WARN semafor No README data
npm WARN semafor No license field.
pi@raspberrypi-llovet:~/semafor $
- fem package.json :
pi@raspberrypi-llovet:~/semafor $ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See "npm help json" for definitive documentation on these fields
and exactly what they do.
Use "npm install <pkg> --save" afterwards to install a package and save it as a dependency in the package.json file.
Press ^C at any time to quit.
name: (semafor)
version: (1.0.0)
description:
entry point: (1-sem.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /home/pi/semafor/package.json:
{
"name": "semafor",
"version": "1.0.0",
"description": "",
"main": "1-sem.js",
"dependencies": {
"connect": "^3.4.1",
"express": "^4.14.0",
"rpi-gpio": "^0.7.0",
"serve-static": "^1.11.1"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this ok? (yes) yes
pi@raspberrypi-llovet:~/semafor $
Millorem les dependencies:
- npm install connect --save
- npm install serve-static --save
- npm install serialport --save
- npm install rpi-gpio --save
- npm install morgan --save
- npm install python-shell --save {call python to take a picture}
- npm install socket.io --save {notification server}
- npm install xml2json --save {notification server}
Now the package with the dependencies is :
pi@raspberrypi-llovet:~/semafor $ cat package.json
{
"name": "semafor",
"version": "1.0.0",
"description": "",
"main": "1-sem.js",
"dependencies": {
"connect": "^3.4.1",
"express": "^4.14.0",
"rpi-gpio": "^0.7.0",
"serialport": "^3.1.2",
"serve-static": "^1.11.1"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
- get webgpio.zip, web project
pi@raspberrypi-llovet:~/semafor $ sudo wget www.privateeyepi.com/downloads/webgpio.zip
--2016-06-21 12:37:05-- http://www.privateeyepi.com/downloads/webgpio.zip
Resolving www.privateeyepi.com (www.privateeyepi.com)... 104.197.26.196
Connecting to www.privateeyepi.com (www.privateeyepi.com)|104.197.26.196|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 24530 (24K) [application/zip]
Saving to: {webgpio.zip}
webgpio.zip 100%[========================================================>] 23.96K 137KB/s in 0.2s
2016-06-21 12:37:05 (137 KB/s) - {webgpio.zip} saved [24530/24530]
- sudo unzip webgpio.zip
pi@raspberrypi-llovet:~/semafor $ sudo unzip webgpio.zip
Archive: webgpio.zip
inflating: onoff.ims
inflating: css/index-maina.css
inflating: geometry/buttonframe1geo1shd1pg1p12.png
inflating: geometry/buttonframe2geo11shd3pg1p12.png
inflating: geometry/obj10title27pg1p12.png
inflating: geometry/obj6title11pg1p12.png
inflating: geometry/obj8title13pg1p12.png
inflating: webgpio.service
inflating: webgpio.js
inflating: webserial.js
inflating: index.html
pi@raspberrypi-llovet:~/semafor $
- start application : node webgpio.js
pi@raspberrypi-llovet:~/semafor $ node webgpio.js
Server running at http://192.168.1.123/
- from Android (client), browse http://youripaddress:8000/
configuracio del pinout
On s'escull (software) que els pins 15, 16 i 18 seran de sortida ?
We use this
package
And we code
var gpio = require( 'rpi-gpio' ) ; // GPIO pin access
gpio.setup( k_Groc, gpio.DIR_OUT, function( err ) { // k_Groc is 15
apagarLuz( k_Groc ) ; // gpio.write( miPin, false, function(err) {
} ) ;
git
Create an empty git :
pi@raspberrypi-llovet:~/semafor $ git init
Initialized empty Git repository in /home/pi/semafor/.git/
pi@raspberrypi-llovet:~/semafor $ git config -l
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
Despres fem
- crear ".gitignore" i hi posem "oldies", directori amb fitxers vells
- git add . {afegit tots els fitxers al projecte}
- git config --global --add user.name sebas
- git config --global --add user.email sebas@gmail.com
- git commit -am "v1.0.b contingut inicial, funciona" {commit}
pi@raspberrypi-llovet:~/semafor $ git commit -am "v1.0.b contingut inicial, funciona"
[master (root-commit) 8e3cd3a] v1.0.b contingut inicial, funciona
15 files changed, 558 insertions(+)
create mode 100644 .gitignore
create mode 100644 1-sem.js
create mode 100644 2-proves.py
create mode 100644 2-webcam.py
create mode 100644 package.json
create mode 100644 public/css/sem.css
create mode 100644 public/favicon.ico
create mode 100644 public/images/1-webcam.png
create mode 100644 public/images/2-webcam.jpg
create mode 100644 public/images/3-webcam.gif
create mode 100644 public/images/blanc.jpg
create mode 100644 public/index.html
create mode 100644 public/initial.htm
create mode 100644 readme.md
create mode 100755 ru0.sh
pi@raspberrypi-llovet:~/semafor $
- entrar a
github.com i crear repositori
semafor
- git remote add origin
https://github.com/sebastianet/semafor.git
pi@raspberrypi-llovet:~/semafor $ git remote -v
origin https://github.com/sebastianet/semafor.git (fetch)
origin https://github.com/sebastianet/semafor.git (push)
- git push -u origin master {usr/pwd}
pi@raspberrypi-llovet:~/semafor $ git push -u origin master
Username for 'https://github.com': sebastianet
Password for 'https://sebastianet@github.com':
Counting objects: 20, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (17/17), done.
Writing objects: 100% (20/20), 123.39 KiB | 0 bytes/s, done.
Total 20 (delta 0), reused 0 (delta 0)
To https://github.com/sebastianet/semafor.git
* [new branch] master -> master
Branch master set up to track remote branch master from origin.
pi@raspberrypi-llovet:~/semafor $
- we got all ok in
github
- from now on, all we do is
- git commit -am "comentari"
- git push -u origin master {usr/pwd}
Sequencia de comandes
Para cualquier orden que no sea sólo modificar el estado actual sino activar una determinada secuencia,
necesitarás utilizar setTimeout y APIs similares:
API timers
Básicamente para el bucle verde-amarillo-rojo, has de hacer:
int luz = 0; // 0=verde, 1=amarillo, 2=rojo
function cambiarLuces() {
apagarLuz(luz) ;
luz = (luz + 1) % 3 ;
encenderLuz(luz) ;
}
setInterval( cambiarLuces, 1000 ) ; // schedules repeated execution of "callback" every "delay" milliseconds.
Puedes llevar la cuenta de cuántas veces se ha ejecutado cambiarLuces() y cancelar el setInterval, etc.
Get a pic/frame every 5 sec
Podem cridar a
python des node.js ?
El python faria "openCV()" + "cv2.save('/tmp/foto.png', frame)"
Compte : com que node corre com "root" per poder accedir al GPIO,
el fitxer PNG es crea amb owner "root:root".
Per canviar-ho :
import os
import pwd
os.chown( 'image.png', pwd.getpwnam('pi').pw_uid, pwd.getpwnam('pi').pw_gid ) ;
Si vols ser una mica mes descarat, fas aixi :-)
os.system('chown pi:pi {}'.format(image_filename))
openCV install at raspberry
- sudo apt-get update ; sovint
- sudo apt-get install libhighgui2.4 libopencv-imgproc2.4 libopencv-core2.4 python-opencv
- sudo apt-get install python-opencv
- sudo apt-get install python-numpy
Provem si funciona (des un putty fer export DISPLAY=:0 abans) :
pi@raspberrypi-llovet:~/semafor $ cat 4-webcap.py
import cv2
import sys
# 0 = primera webcam
cap = cv2.VideoCapture(0)
if not cap:
print 'no trobo la webcam'
sys.exit(1)
while(cap.isOpened()):
ret, frame = cap.read()
imggray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('webcam', imggray)
if cv2.waitKey(1) & 0xFF == ord('q'):
print 'adeu'
break
cap.release()
cv2.destroyAllWindows()
Hi ha una perdua de frames. Esta explicat aqui.
Prova de fer:
sudo vi /boot/cmdline.txt
afegeix al principi de la linia "dwc_otg.fiq_fsm_mask=0x5"
A mes, per no tenir problemes amb el teclat USB, posem
sudo vi /boot/
config.txt
# Albert, 20160704 - USB current problems
usb_max_current=1
Si hi ha el teclat USB, la foto te problemes de sincronisme tot i els 2 "hacks".
Reboot : "sudo reboot" o "sudo shutdown -r now"
openCV constants
# 0. CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds.
# 1. CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next.
# 2. CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file
# 3. CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream.
# 4. CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream.
# 5. CV_CAP_PROP_FPS Frame rate.
# 6. CV_CAP_PROP_FOURCC 4-character code of codec.
# 7. CV_CAP_PROP_FRAME_COUNT Number of frames in the video file.
# 8. CV_CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() .
# 9. CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode.
# 10. CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras).
# 11. CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras).
# 12. CV_CAP_PROP_SATURATION Saturation of the image (only for cameras).
# 13. CV_CAP_PROP_HUE Hue of the image (only for cameras).
# 14. CV_CAP_PROP_GAIN Gain of the image (only for cameras).
# 15. CV_CAP_PROP_EXPOSURE Exposure (only for cameras).
# 16. CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB.
# 17. CV_CAP_PROP_WHITE_BALANCE Currently unsupported
# 18. CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend)
How to read a pic in NGS 300
From here :
#! /usr/bin/env python
import cv2
import sys
vc = cv2.VideoCapture(0)
vc.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH,320)
vc.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT,240)
if not vc.isOpened():
sys.stderr.write('could not connect to camera! \n')
sys.exit(1)
for count in range(0,5):
print '1) fer foto num ' + str(count)
success,frame = vc.read()
if not success:
sys.stderr.write('could not read image from cam \n')
sys.exit(1)
if ( count == 4 ):
print '2) gravar foto num ' + str(count)
cv2.imwrite( 'captura_%02d.png' % count, frame )
vc.release()
vc = None
Al Raspall ho tenim implementat aqui : /home/pi/semafor/4_foto_verbose.py !
HTML 304 return code
Quan fem que node i python facin una foto i la guardin al filesystem,
el servidor retorna 304, i el client deix de mostrar la foto nova.
Provem
// ... Express.js app instantiation
app.disable( 'etag' ) ;
// ... Express.js app routes
secret express js settings
Clear Cache : press CTRL+SHIFT+DELETE in any browser.
Use
Fiddler to monitor/catch the traffic between browser and server.
Set "Last-Modified" to now to avoid "304 Not Modified"
Add "/*" handler - don’t forget to call next()
Ponerlo antes que el código que maneja las peticiones más específicas, para que se active antes.
En caso contrario, si este handler se activa cuando ya se ha enviado la respuesta, ya es tarde para modificar las cabeceras.
app.get('/*', function(req, res, next){
res.setHeader('Last-Modified', (new Date()).toUTCString());
next();
});
vlasenko
As 304 is fixed and pic is not updated, we delete the file manually
fs unlink
Make it run on boot
You can define things to run on boot in /etc/rc.local.
In that shell script, you don't have the same path as when you log in, so just running node app.js won't do the trick.
What does work, is running one command as the default "pi" user.
Because that user does have node in his path, the command is known.
su pi -c 'node /home/pi/server.js < /dev/null &'
I suggest using an absolute path to your Node.js-file just to make sure.
Run a python script at boot
url
Send email when wlan comes up
pi@raspberrypi-llovet:~ $ cat /etc/network/if-up.d/envia_emilio
#!/bin/bash
# Check for specific interface
if [ "$IFACE" = "wlan0" ]; then
/home/pi/sendemail/snd_1.sh
fi
Keep in mind : files in this directory must not have .sh extension
Destinations are :
- raspall : llovetbasura@gmail.com, bisc2k9@gmail.com
- odin : bisc2k9@gmail.com, llovetbasura@gmail.com
- henry : bisc2k9@gmail.com, henrybrossa@gmail.com
[]
users and groups
We have user "sebas" similar to "pi" :
pi@raspall:~ $ groups pi
pi : pi adm dialout cdrom sudo audio video plugdev games users input netdev spi i2c gpio
semafor APP configuration and user's guide
internal URL : 192.168.0.123:1212
external URL : raspall.hopto.org:9007
router Vodafone : mapear port extern 9007 cap a IP = 192.168.0.123, port 1212
APP usr = <any>
APP pwd = "."
canvi de router -> reconfigurar el semàfor
Sempre hem de fer, en aquest ordre :
- apagar el Raspall
- conectar el teclat USB-A al Raspall
- conectar el ratolí USB-A al Raspall
- conectar la pantalla HDMI al Raspall
- engegar el Raspall
- en 1 minut, ha de sortir un quadre de vora un pam quadrat amb tots els colors
- quan tinguem un escriptori (pot trigar 3 o 4 minuts), a dalt a la dreta hi ha un simbol de wifi, on hem de posar el SSID i la clau de pas del nou router
en altres instalacions ...
Llavors, podem fer els pasos estandard :
$ sudo raspi-config -> "System Options" -> "Wireless LAN" -> enter SSID and PWD
O podem editar wpa_supplicant.conf ...
o be fer anar el meu shell using nmcli :
$ cat wifi.sh
#!/bin/bash
iNum=$#
echo "We have ("$iNum") parameters"
if [ $iNum -eq 2 ]
then
sz_SSID=$1
sz_PWD=$2
echo "+++ SSID is ("$sz_SSID")."
echo "+++ PWD is ("$sz_PWD")."
sudo nmcli radio wifi on #
sudo nmcli dev wifi connect $sz_SSID password "$sz_PWD" #
else
echo "--- we need 2 parameters, SSID and PWD"
fi
exit 0
Aixo no se si guarda els valors per despres del proper re-inici
router 20250321
Dades :
- Vodafone Station -> UG (42 pages)
- model : Sagemcom 253678071
- MAC : 5c.fa.25.96.6e.2b
- URL : http://192,168.0.1 ; user : vodafone ; pwd router : JZNYWM3A
- xarxa 2,4 GHz : vodafone6E2B ; xarxa 5 GHz : vodafone6E2B-5G -> VodafoneAC9B + VodafoneAC9B-5G
- clau de pas wifi : FGZMDJNWKZMWQG -> 8F9399ULJ93W98 (as oldie)
Objectiu : separar les dues xarxes i posar una clau de pas senzilla.
aire condicionat
Dades :
- fabricant : Mitsubishi
- model : MSZ-BT35VGK
- serial number : 0010123 T
Wi-Fi interface :
- MAC : b8.b7.f1.ca.1d.17
- id : 2024.11.30.009
- SSID : ME-N200014992
- key : r58kgcff8
Objectiu : conectar la maquina a Internet per poder-la fer anar remotament.
Diu : incorpora conexión WiFi a través de MELCloud
Tambe : WiFi incluido de serie y compatible con Alexa
Set up a connection between the Wi-Fi interface and the Router.
• Refer to the SETUP MANUAL and SETUP QUICK REFERENCE GUIDE provided with the unit.
• For SETUP MANUAL, please go to the website http://www.melcloud.com/Support -> WiFi interface
• For MELCloud User Manual, please go to the website http://www.melcloud.com/Support -> MELCloud -> PDF
RMTC - remote control
*** Test it here ***
We want to control the Raspberry pins from a remote smartphone using a
browser
Shall start from
this article
and this
project, with
dotenv supported :
- posem "sag" a sudoers
pi@odin:~ $ sudo usermod -aG sudo sag
- posem el sistema al dia - fer-ho sovint
sag@odin:~ $ sudo apt-get update
- instalem el package
sag@odin:~ $ git clone https://github.com/tutRPi/Raspberry-Pi-Simple-Web-GPIO-GUI
Cloning into 'Raspberry-Pi-Simple-Web-GPIO-GUI'...
remote: Enumerating objects: 85, done.
remote: Total 85 (delta 0), reused 0 (delta 0), pack-reused 85
Unpacking objects: 100% (85/85), done.
Checking connectivity... done.
sag@odin:~ $
- instalem els requisits :
sag@odin:~ $ cd Raspberry-Pi-Simple-Web-GPIO-GUI/
sag@odin:~/Raspberry-Pi-Simple-Web-GPIO-GUI $ npm install
- engeguem la aplicacio :
sag@odin:~/Raspberry-Pi-Simple-Web-GPIO-GUI $ sudo npm start
Obtenim un error extrany -
issue
Solution from
here : modify "main.js" to contain "'use strict;'" at the very beginning
sag@odin:~/Raspberry-Pi-Simple-Web-GPIO-GUI $ vi /home/sag/Raspberry-Pi-Simple-Web-GPIO-GUI/node_modules/dotenv/lib/main.js
'use strict';
Some issues
- verifiquem a quin port es troba :
sag@odin:~ $ sudo netstat -tulpn | grep LISTEN
[sudo] password for sag:
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 557/sshd
tcp6 0 0 :::80 :::* LISTEN 19965/node
- hi accedim :
sag@odin:/tmp $ wget localhost:80
--2019-02-14 15:14:53-- http://localhost/
Resolving localhost (localhost)... ::1, 127.0.0.1
Connecting to localhost (localhost)|::1|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 12778 (12K) [text/html]
Saving to: {index.html.1}
index.html.1 100%[============================================>] 12.48K --.-KB/s in 0s
2019-02-14 15:14:54 (67.9 MB/s) - âindex.html.1â saved [12778/12778]
- configurem al fitxer ".env"
sag@odin:~/Raspberry-Pi-Simple-Web-GPIO-GUI $ cat .env
PORT=1212
que es llegeix aixi
require('dotenv').config() ; // sudo apt-get install dotenv
var port = ( process.env.PORT || '1213' ) ; // sudo npm install --save dotenv-extended
- obrim el router per arribar a 192.168.1.123:1212 des el port exterior 9009
Aixi, un acces a http://80.31.158.144:9009/ treu :
$ engega.sh
Today external IP {80.31.158.144}.
> Raspberry-Pi-Simple-Web-GPIO-GUI@1.0.0 start /home/sag/Raspberry-Pi-Simple-Web-GPIO-GUI
> node ./bin/www "?"
GET / 200 2894.581 ms - 12778
GET /stylesheets/style.css 200 5.908 ms - 1095
GET /stylesheets/bootstrap-toggle.min.css 200 3.115 ms - 1590
GET /javascripts/bootstrap-toggle.min.js 200 6.655 ms - 4129
GET /stylesheets/bootstrap.min.css 200 4.531 ms - 121200
GET /javascripts/client.js 200 1.791 ms - 504
GET /javascripts/jquery.min.js 200 8.885 ms - 95821
GET /javascripts/bootstrap.min.js 200 7.843 ms - 37045
GET /favicon.ico 404 50.733 ms - 1696
POST /ajax 200 109.900 ms - 24
POST /ajax 200 5.259 ms - 25
- fem que engegui amb la maquina :
$ cat /etc/rc.local
$ /usr/local/bin/odin_restart ->
/home/sag/Raspberry-Pi-Simple-Web-GPIO-GUI/engega.sh ->
/usr/bin/node /home/sag/Raspberry-Pi-Simple-Web-GPIO-GUI/bin/www
- veiem el seu funcionament : "tail -f /home/sag/logs/rmtc.log"
Tots els pins son de sortida !
Compte que tot son sortides, using
rpio package :
$ cat ./routse/ajax.js
var rpio = require('rpio') ;
rpio.init({mapping: 'gpio'});
rpio.open(req.body.gpio, rpio.OUTPUT, + req.body.status);
rpio.write(req.body.gpio, + req.body.status);
res.contentType('json');
res.send({ gpio: req.body.gpio, status: req.body.status });
Ruta del manegament de la bombeta des un mobil
- el client engega un browser al seu telefon
- que està conectat a la wifi "GAS2"
- que és proporcionada per el router ZyXel
- i està conectat a la meva antena "NanoBeam M5"
- que es conecta a la antena "Rocket 5" del Campanar
- que te un enllaç de sues antenes "LiteBeam AC" amb Can Sostres
- on hi ha un router de Fibra Òptica de Timofònica
- que ens porta a Internet
- on està conectat el meu router de Fibra Òptica
- que proporciona la xarxa wifi "enxaneta"
- on es conecta el Raspberry "odin"
- que te un sistema operatiu "Raspbian"
- on s'executa una APP escrita en "nodeJS"
- que permet manegar els pins GPIO
- on hi ha un transistor SC107
- que manega un SSR CX205D5 (AC load)
- que te com a càrrega una bombeta incandescent de 50 watts
RMTC links
- cable plà :
- breadboard :
- cable + breadboard :
Aliexpress 1,54 € + 2,33 € envio
- compte amb la caixa del Raspberry :
caixa Diotronic amb
"Ranuras bajo la parte superior de la carcasa para el acceso de cable plano externo a GPIO" - 7€77
Fem una foto remota
*** Test it here ***
Si en RMTC engega/atura un LED vora el Raspberry de casa, per verificar-ho remotament
em cal una foto ...
Comencem servint algunes pagines, as INDEX.HTML :
server
- baixem el projecte :
sag@odin:~ $ git clone https://github.com/scotch-io/express-sendfile.git
Cloning into 'express-sendfile'...
remote: Enumerating objects: 9, done.
remote: Total 9 (delta 0), reused 0 (delta 0), pack-reused 9
Unpacking objects: 100% (9/9), done.
Checking connectivity... done.
sag@odin:~ $
- instalem els requisits :
sag@odin:~ $ cd express-sendfile/
sag@odin:~/express-sendfile $ npm install
- instalem "dotenv" : npm install dotenv
- posem "PORT=2415" al fitxer ".env"
- corregim "/home/sag/express-sendfile/node_modules/dotenv/lib/main.js" per contenir "'use strict';"
- engeguem la aplicacio :
sag@odin:~/express-sendfile $ node server.js
- verifiquem que funciona : http://odin:8081/
- posem "index.html" sota "./public/" i "photo.css" sota "./public/css/"
- dins index.html posem "client.js" amb el codi JavaScript del client
- partim index.html en diferents sub-parts i hi posem la hora
- des el client agafem control del "click" demanant la foto,
rebem la resposta i posem la foto en el lloc adient
- els missatges "console.log" del codi del client es poden veure amb Chrome + PF12 !
- problema amb el python-shell :
% node server.js
/home/sag/express-sendfile/node_modules/python-shell/index.js:29
function extend(obj, ...args) {
^^^
SyntaxError: Unexpected token ...
at exports.runInThisContext (vm.js:53:16)
- versio del node : 5.12
- actualitzem tot (20 minuts) :
$ sudo apt full-upgrade -y
En sortim amb el mateix node v5.12.0 i el mateix problema
En Pere diu : "Has de passar al darrer node amb ES6"
- podem forçar la versio 0.4.0 de python-shell
aixi
$ npm install python-shell@0.4.0 --save
- posem node 11 :
guia molt complerta,
guia oficial
- update our Debian apt package repository to include the NodeSource packages :
$ curl -sL https://deb.nodesource.com/setup_11.x | sudo -E bash -
- install latest node.js :
$ sudo apt-get install -y nodejs
- resultat :
sag@odin:~/express-sendfile $ node -v
v11.13.0
- fem una primera foto amb la Logitech
$ tail /var/log/syslog
Feb 18 19:21:54 odin kernel: [78492.007076] usb 1-1.5: new full-speed USB device number 4 using dwc_otg
Feb 18 19:21:54 odin kernel: [78492.113764] usb 1-1.5: New USB device found, idVendor=046d, idProduct=08da
Feb 18 19:21:54 odin kernel: [78492.113784] usb 1-1.5: New USB device strings: Mfr=0, Product=0, SerialNumber=0
Feb 18 19:21:55 odin systemd-udevd[26127]:
failed to execute '/lib/udev/mtp-probe' 'mtp-probe /sys/devices/platform/soc/3f980000.usb/usb1/1-1/1-1.5 1 4':
No such file or directory
Instalem
$ sudo apt-get install libmtp-runtime
Feb 18 19:34:39 odin kernel: [79256.802757] usb 1-1.5: USB disconnect, device number 4
Feb 18 19:34:44 odin kernel: [79261.391894] usb 1-1.3: new full-speed USB device number 5 using dwc_otg
Feb 18 19:34:44 odin kernel: [79261.498597] usb 1-1.3: New USB device found, idVendor=046d, idProduct=08da
Feb 18 19:34:44 odin kernel: [79261.498619] usb 1-1.3: New USB device strings: Mfr=0, Product=0, SerialNumber=0
Feb 18 19:34:44 odin mtp-probe: checking bus 1, device 5: "/sys/devices/platform/soc/3f980000.usb/usb1/1-1/1-1.3"
Feb 18 19:34:44 odin mtp-probe: bus: 1, device: 5 was not an MTP device
Algo hi ha
sag@odin:~/express-sendfile $ lsusb
Bus 001 Device 005: ID 046d:08da Logitech, Inc. QuickCam Messanger
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Veiem
sag@odin:~/express-sendfile $ dmesg
[79261.391894] usb 1-1.3: new full-speed USB device number 5 using dwc_otg
[79261.498597] usb 1-1.3: New USB device found, idVendor=046d, idProduct=08da
[79261.498619] usb 1-1.3: New USB device strings: Mfr=0, Product=0, SerialNumber=0
But
sag@odin:~/express-sendfile $ v4l2-ctl -V
Failed to open /dev/video0: No such file or directory
Tambe
sag@odin:~/express-sendfile $ sudo modprobe bcm2835-v4l2
modprobe: ERROR: ../libkmod/libkmod.c:557 kmod_search_moddep() could not open moddep file
'/lib/modules/4.4.11-v7+/modules.dep.bin'
sag@odin:~/express-sendfile $ vcgencmd get_camera
VCHI initialization failed -> sudo usermod -aG video sag
sag@odin:~/express-sendfile $ sudo vcgencmd get_camera
supported=0 detected=0
Instalem
sag@odin:~/express-sendfile $ sudo apt-get install motion
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
libc-ares2 libcwiid1 libjs-prettify libllvm3.7 libqscintilla2-11 libqscintilla2-l10n libqt4-network libqt4-xmlpatterns libqtwebkit4 libruby1.9.1
libruby1.9.1-dbg libtcl8.5 libtcltk-ruby1.9.1 libtk8.5 libv8-3.14.5 ri1.9.1 ruby1.9.1 ruby1.9.1-dev ruby1.9.1-examples ruby1.9.1-full ruby1.9.3
supercollider supercollider-common supercollider-ide supercollider-language supercollider-supernova tcl8.5 tk8.5
Use 'apt-get autoremove' to remove them.
Suggested packages:
mysql-client postgresql-client
Recommended packages:
ffmpeg
The following NEW packages will be installed:
motion
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Reboot and
sag@odin:~ $ dmesg | grep gspca
[ 3.075290] gspca_main: v2.14.0 registered
[ 3.080873] gspca_main: gspca_zc3xx-2.14.0 probing 046d:08da
[ 4.498065] input: gspca_zc3xx as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.3/input/input0
[ 4.500283] usbcore: registered new interface driver gspca_zc3xx
sag@odin:~/express-sendfile $ sudo v4l2-ctl -V
Format Video Capture:
Width/Height : 640/480
Pixel Format : 'JPEG'
Field : None
Bytes per Line: 640
Size Image : 115790
Colorspace : JPEG (JFIF/ITU601)
Flags :
Funciona si engego des user=pi, no si es user=sag - si que va si faig "sudo python /home/pi/semafor/4_foto_verbose.py"
apt-cache policy libmtp9
Can use standard USB webcam - fswebcam :
If you are not using the default pi user account,
you need to add your username to the video group,
otherwise you will see 'permission denied' errors.
- dirigim el port extern 8015 cap a 192.168.1.123:2415
Aixi un acces a myraspiodin.hopto.org:8815 ens mostra
save the project to github
Again and again I write this down :
- go into the directory containing the project
- type git init
- create a .gitignore file to indicate all of the files you don’t want to track, as "node_modules"
- type git add . to add all of the relevant files
- type git commit -am "v1.0.a"
You’ve now got a local git repository. If you want the thing to have a home on github, do
- goto github
- (github) log in to your account
- click the new repository button in the top-right (sign "+")
You’ll have an option there to initialize the repository with a README file, but I don’t.
- click the “Create repository” button - named "Envia_Foto"
- (odin) git remote add origin git@github.com:sebastianet/Envia_Foto.git
or git remote add origin https://github.com/sebastianet/Envia_Foto.git
- if there is an error we use "git remote rm origin"
- to list the origin we use "git remote -v"
- (odin) git push -u origin master - provide usr+pwd to send the code
- and here you are !
url
eines ben practiques per aturar i engegar la APP
Per aturar la app fem :
sag@odin:~/express-sendfile $ cat 0_atura.sh
#!/bin/bash
if [ `id -u` -ne 0 ]
then
echo "--- Must be running as root"
exit 1
fi
strID='express-sendfile'
echo "+++ (1) abans"
ps -ef | grep $strID | grep -v grep
toKILL=$(ps -ef | grep $strID | grep -v grep | awk '{print $2}')
echo ">>> (2) to stop ($strID) we want to kill ($toKILL)."
if [[ -n $toKILL ]]
then
kill $toKILL
fi
echo "+++ (3) despres"
ps -ef | grep $strID | grep -v grep
exit 0
Per engegar la app fem
sag@odin:~/express-sendfile $ cat 1_engega.sh
#!/bin/bash
if [ `id -u` -ne 0 ]
then
echo "--- [engega.sh] Must be running as root"
exit 1
fi
fTZ="/home/sag/logs/photo_server.log"
szOUT="==== [`date -R`] === ($0) === (v1.c) === start node PHOTO SERVER, user($USER) host($HOSTNAME)"
echo -e "\n$szOUT" >> $fTZ
szOUT="$szOUT tracefile ($fTZ)."
logger -i -p user.info $szOUT
ipEXT=$(curl -s icanhazip.com); // curl -m 2 -s http://checkip.amazonaws.com
szIP="[`date -R`] external IP is {$ipEXT}. External port 8815, internal 2415/8080."
echo $szIP >> $fTZ
# si ve de /etc/rc.local ja es ROOT
/usr/bin/node /home/sag/express-sendfile/server.js >> $fTZ 2>&1 &
rv=$?
echo "[engega.sh] node photo server rc is ("$rv")." >> $fTZ
ps -ef | grep node | grep -v grep >> $fTZ
# sudo cat /var/log/messages
# cat /home/sag/logs/photo_server.log
# tail -f /home/sag/logs/photo_server.log
exit 0
Per veure com estan tots els nodes fem :
sag@odin:~/express-sendfile $ cat 2_estat.sh
#!/bin/bash
clear
echo "(1) +++ estat del node"
ps -ef | grep node | grep -v grep
echo "(2) +++ ports"
sudo netstat -tulpn | grep LISTEN | grep node
echo "(3) +++ la meva IP externa"
curl -m 2 -s icanhazip.com ; curl -m 2 -s http://checkip.amazonaws.com
exit 0
save the JSBIN project to GIST
timer at client
JSBIN,
GIST,
how to provide server
Pin de entrada
Després de parlar amb en Ramon (20190503, 22h), vull llegir un pin del GPIO de entrada
Cablegem aixi :
-----------------.
|
+ 3,3 v pin 17 | --------o
| |
| ---
| [ rele ]
| ---
| |
GPIO 16, pin 36 | ----.---o
| |
| | |
| | | 22 K
| | |
| |
gnd pin 39 | ----.
|
-----------------.
I el software es senzill :
sag@odin:~/gpio_python $ cat entrada.py
#!/usr/bin/env python
# executem amb "sudo ./entrada.py"
import RPi.GPIO as GPIO # import GPIO library
from time import sleep # import time library to have "sleep"
print "Version GPIO =", GPIO.VERSION # mostrar la versio de GPIO
GPIO.setmode(GPIO.BOARD) # escollim numeracio "com a la placa"
ENTRADA = 36 # com entrada fem servir el tercer pin de baix a la dreta (see command "pinout") - GPIO16, pin 36
SORTIDA = 37 # com sortida fem servir el penultim pin de l'esquerra (see command "pinout") - GPIO26, pin 37
GPIO.setup(ENTRADA, GPIO.IN) # set pin 36 / GPIO16 as input (button)
GPIO.setup(SORTIDA, GPIO.OUT) # set pin 37 / GPIO26 as output (LED)
try:
while True: # this will carry on until you hit CTRL+C
if GPIO.input(ENTRADA): # if port 36 == 1
print "+++ pin 36 is 1/HIGH/True - led ON +++" # then print "ON"
GPIO.output(SORTIDA, 1) # and set port/pin value to 1/HIGH/True
else: # else
print "--- pin 36 is 0/LOW/False - led OFF ---" # print "OFF"
GPIO.output(SORTIDA, 0) # and set port/pin value to 0/LOW/False
sleep(0.1) # wait 0.1 seconds
finally: # this block will run no matter how the try block exits
GPIO.cleanup() # clean up after yourself
No cal dir que funciona perfectament.
Ara falta crear una pàgina HTML.
wsm
We serve static pages from the "public" directory so the only code we need is :
sag@odin:~/gpio_python $ cat wsm.js
app.set( 'mPort', process.env.PORT || 80 ) ; // need 80 for wget
var szHostName = require('os').hostname() ; // https://nodejs.org/api/os.html
var szIP = process.argv [ 2 ] ; // local IP passed from shell
app.use( express.static( path.join( __dirname, '/public' ) ) ) ; // serve static files
let szId = `*** MinWebSrv listening on port [` + szIP + ':' + app.get('mPort') + `], host {` + szHostName + `} *** `
app.listen( app.get( 'mPort' ), () => {
console.log( szId )
} ) ;
put the project to github
To fill gpio_python_input repository we did :
- sudo npm install -g npm
- npm init
- npm install express --save
- (github) https://github.com/sebastianet/gpio_python_input.git
- $ echo "# gpio_python_input" >> README.md
- $ git init
- edit ".gitignore" to include "node_modules"
- $ git rm -r --cached node_modules
- $ git add .
- $ git commit -am 'v 1.0 - first commit'
- $ git remote add origin https://github.com/sebastianet/gpio_python_input.git
- $ git remote -v
- $ git push origin master
RSPI and Alexa
I si volguessim fer anar una App del Rspi (server) fent servir Alexa (client) ?
Exemple : llegit temperatura o valos Fronius amb una frase a Alaxe ...
I si des el Rspi (client) volem fer anar un servidor que pot manegar Alexa (server) ?
Exemple : encendre el llum del menjador
URLs per controlar el RSPI amb Alexa
Sensor de soroll per Roda
Ferralla, sensors
See KY-037 i KY-038 specs,
read KY-038 datasheet
- 1 pin d salida digital, 0,86 €
- KY-037, 0,63 € + 1,99 = 2,62 {***} o KY-038
- AZDelivery KY-037 : 1 = 4,99 €, 3 = 6,49 €, 5 = 7,49 €
Esquema conexionat
-----------------.
|
+ 5 v pin 2 | --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- .
| |
+ 3,3 v pin 17 | ------------. |
| | |
| | | |
| | | Rc |
| | | | (+)
| | |
GPIO 16, pin 36 | <-- <-- <---. (c) |
| | |
| ( | ) .--------.
| ( | ) Rb | |
| ( | ) -------- | Sound |
| ( ========= ) --- (b) --- | | <-- <-- <-- (DO) --- | Sensor |
| ( \ / ) -------- | |
| ( \ / ) .--------.
| ( | ) |
| | | (-)
| | (e) |
gnd pin 39 | ------------.-------------------------------------------------------.
|
-----------------.
Quatre calculs :
d'entrada, suposem Rb = 100 k and Rc = 10 k
if D0 == "0" then GPIO 16 := "1", 3,3 V
if D0 == "1" and GPIO 16 == "0"
then
Ic = 3,3 - 0,2 / 10 = 0,31 mA = 310 uA
Ib = 5 - 0,7 / 100 = 43 uA
ens cal una β de 10
si volem Ic = 3 mA, llavors Rc = 3,3 - 0,2 / 3 = 1 k
si volem Ic = 1 mA, llavors Rc = 3,3 - 0,2 / 1 = 3 k
Final : BC 207 A, Rb = 100 K, Rb = 1K5
Per fer proves ...
Tenim una lectura cada segon ... (inexacte ...)
sag@odin:~ $ /home/sag/gpio_python/llegir_soroll_pin36.py -> ./dades_soroll/soroll_CSV_YYYY_MM_DD.csv
... ens cal un soroll "fixe" ...pixabay
Detalls de la ferralla
SC107
Specs :
Type Designator : SC107
Material of transistor : Si
Polarity : NPN
Maximum collector power dissipation (Pc), W : 0.25
Maximum collector-base voltage |Ucb|, V : 50
Maximum collector-emitter voltage |Uce|, V : 45
Maximum emitter-base voltage |Ueb|, V : 5
Maximum collector current |Ic max|, A : 0.1
Maksimalna temperatura (Tj), °C : 125
Transition frequency (ft), MHz : 165
Forward current transfer ratio (hFE), min : 120
Package of SC107 transistor : X13 (B-C-E)
BC547C
Specs :
Type Designator : BC547C
Material of transistor : Si
Polarity : NPN
Maximum collector power dissipation (Pc), W : 0.5
Maximum collector-base voltage |Ucb|, V : 50
Maximum collector-emitter voltage |Uce|, V : 45
Maximum emitter-base voltage |Ueb|, V : 6
Maximum collector current |Ic max|, A : 0.1
Maksimalna temperatura (Tj), °C : 150
Transition frequency (ft), MHz : 200
Forward current transfer ratio (hFE), min : 420
Package of BC547 transistor : TO92 (C-B-E)
Calculs circuit transistor amb un LED al colector
Sabem que V(led encès) = 1,8 v.
Volem Ic = 5 mA o menys.
Aixi, la Rc per tenir 5mA és ( 5 v - 0,2 v - 1,8 v ) / 5 mA = 3 v / 5 mA = 0,6 k
(Std) Amb una Rc de 1k permetem el pas de Ic = ( 5 v - 0,2 v - 1,8 v ) / 1k = 3 mA
(Std) Amb una Rc de 1k5 permetem el pas de Ic = ( 5 v - 0,2 v - 1,8 v ) / 1k5 = 2 mA
Si Rb és 100k, llavors Ib és ( 3,3 - 0,7 ) v / 100 k = 26 uA.
Amb una Hfe(min) = 120 assegurem que el transistor estigui saturat.
Calculs circuit transistor amb un SSR al colector
El SSR equival a una resistencia de 300 ohms, 0,3k.
Així, Ic = 5 v - 0,2 v / 0,3 k = 16 mA
Ens cal Ib > 16 mA / 120 = 130 uA
Rb = 3,3 v - 0,7 v / 130 uA = 20 k
Calculs circuit transistor amb un LED i un SSR al colector
Amb el transistor saturat, passen 16 mA pel SSR i 2 mA pel LED (Rc de 1k5).
Resum de components :
- Q : SC107, Hfe(min) = 120, BC547, Hfe(min) = 420
- R3 = Rb = 22 k
- R1 = Rc = 1k5 (o 0,6 k)
- R2 = SSR cx240d5 = 0,3 K
Resum de valors :
- Ib = 3,3 - 0,7 / 22k = 120 uA
- Ic = 16 mA + 2 mA = 18 mA {120 uA * beta 120 = 14 mA}
- V(led) = 1,8 v ; compte amb el model
- I(led) = ( 5 v - 0,2 v - 1,8 v ) / 1k5 = 2 mA ; 5 mA amb R1 = 0,6 k
- I(ssr) = ( 5 v - 0,2 v ) / 0,3k = 16 mA
specs del SSR CX240D5
Comprem CX240D5 per control de carrega de corrent altern (AC load).
SSR = Solid State Relay
Specs CX240D5 :
- pdf,
datasheet
- control voltage from 3 to 15 VDC
- Nominal Input Impedance 300 Ohm
- Typical Input Current 15 mAdc (4,8 v / 0,3 K = 16 mA)
- max load current RMS : 5 A
- DC control (+) :
- pin 3 : +DC control
- pin 4 : -DC control
- pin 1 : AC load
- pin 2 : AC load
- AC control (-) :
- pin 3 : AC control
- pin 4 : AC control
- pin 1 : AC load
- pin 2 : AC load
Compte que els pins de control tenen polaritat !
Si conectem el SSR al colector de un SC107 sense res mes, polaritzat a 5 volts, llavors Ic = 4,8 v / 0,3 k = 16 mA.
specs del SSR CMX200D3
Comprem CMX200D3 per control de carrega de corrent continu (DC load), as
sortida de la cel.la solar cap a la font d'aigua.
Specs CMX200D3 :
- data sheet
CMX series,
CMX200D3
- ontrol voltage from 4 to 10 Vdc
- Nominal Input Impedance : 300 Ohm
- Typical Input Current @ 5 Vdc : 15 mAdc
- Output Operating Voltage Range : 0 - 200 Vdc
- Load Current Range : 0 - 3 Adc
- pinout :
- pin 3 : DC control (+)
- pin 4 : DC control (-)
- pin 1 : DC load (+)
- pin 2 : DC load (-)
7812
Specs 7812 :
- Output Voltage: 12V
- Output Current: 1A
- Package / Case: TO-220
- Input Voltage Max: 35V
- heatsink surface is connected to pin 2
Una BreadBoard per en Albert
Fem quatre calculs :
Vc (saturacio) = 0,2 volts
V led = 1,8 volts
R led = 1 K
I(R led) = 5 - 2 / R led = 3 mA
SSR = CX240D5
R ssr = 0,3 K
I (R ssr) = 5 - 0,2 / R ssr = 16 mA
Ic = 3 mA + 16 mA
V rsp = 3,3 volts
Vb = 0,7 volts
Rb = 22 K
Ib = 3,3 - 0,7 / Rb = 120 uA
Hfe (bc547c) > 420
Ic = Ib * Hfe = 120 uA * 420 = 50,4 mA => *** transistor saturat ***
Escollim per V rsp el pin 37, GPIO26
JS bin
Per fer proves : JS bin
HTML :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<hr>
<p>
<a href="#" id="clkFoto_netejar">Netejar</a> la imatge.
<hr>
<table class="tmy">
<tr>
<td width="60%">
coses
<td width="40%">
<div id="imatge_div">
<img id="imatge_webcam" src="http://usuaris.tinet.cat/sag/arcadi/imatges/copa_europa_2009.jpg" width="900" height="380">
</div>
</table>
<hr>
</body>
</html>
JavaScript :
$( "#clkFoto_netejar" ).click( function() {
console.log( '*** netejar foto posant-ne una de fixe.' ) ;
$( "#imatge_webcam" ).attr( 'src', 'http://usuaris.tinet.cat/sag/imatges/el-ca/raspberrypPi_3_model_b.png' ) ;
}) ; // netejar foto
Xorradetes
Xarxa wifi d'en JALL (201705)
Eina wifi info
.-----------------------------------. .---------------.
| | .======= | Portatil |
| Router Vodafone | wifi | | 192.168.0.33 |
| | =======. .---------------.
| 62.57.74.22 (**) | 192.168.0.1 | |
| | | | .---------------.
.-----------------------------------. .======= | Huawei |
| | 192.168.0.34 |
(**) pot canviar cada 10-20 dies | .---------------.
|
| .----------------.
| | Raspberry |
| | 192.168.0.123 |
.========| |
|-(22) putty | -ext-(9008)
|-(1212) SEMAFOR | -ext-(
9007)
.----------------.
Scan one segment:
c:\ FOR /L %i in (1,1,254) do echo ** (%i) ** && ping -w 500 -n 2 192.168.1.%i
$ sudo nmap -sn 192.168.1.1-255 # ping scan, disable port scan
Enviar email
- install "Simple SMTP" :
sudo apt-get install ssmtp
sSMTP,
MTA
- edit /etc/ssmtp/ssmtp.conf
mailhub=smtp.gmail.com:587
hostname=ENTER YOUR RPI'S HOST NAME HERE
AuthUser=YOU@gmail.com
AuthPass=PASSWORD
useSTARTTLS=YES
My values :
pi@odin:/etc/ssmtp $ cat ssmtp.conf
#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=postmaster
# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=smtp.gmail.com:587
# Where will the mail seem to come from?
#rewriteDomain=
# The full hostname
hostname=odin
# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
#FromLineOverride=YES
# http://www.sbprojects.com/projects/raspberrypi/exim4.php
AuthUser=chicharrito.posada@gmail.com
AuthPass=mycharito
useSTARTTLS=YES
pi@odin:/etc/ssmtp $
- Install mailx :
sudo apt-get install mailutils (mpack)
- test :
mailx destination@domain.com
Cc:
Subject: Test Message
Enter some text here
End with CTRL+D to send
Or
$ mail -s "This is the subject line" someone@example.com < body.txt
$ echo “hello my body” | mail –s “my test” desti@gmail.com
Problemes
Enviar WhatsApp
Yowsup
is a python library that enables you to build application which use WhatsApp service.
Homepage,
yowsup homepage
yowsup is a python library that enables building applications that can communicate with WhatsApp users
It seems that recently yowsup gets detected during registration
resulting in an instant ban for your number right after registering with the code you receive by sms/voice.
Therefore I'd strongly recommend to stop attempting further registrations until I look further into this.
20190627
tutorial ,
howto 20190604
Llibreria
yowsup-cli - a command line interface to Yowsup library.
- sudo apt-get update {sempre}
- sudo apt-get upgrade {delicat}
- sudo rpi-update {molt delicat i no oficial - see "apt raspberrypi-firmware"}
- sudo apt-get install python-dateutil
- sudo apt-get install python-setuptools
- sudo apt-get install python-dev
- sudo apt-get install libevent-dev
- sudo apt-get install ncurses-dev
- install library
pi@raspberrypi-llovet:~ $ git clone git://github.com/tgalal/yowsup.git
Cloning into 'yowsup'...
remote: Counting objects: 7975, done.
remote: Total 7975 (delta 0), reused 0 (delta 0), pack-reused 7975
Receiving objects: 100% (7975/7975), 1.57 MiB | 821.00 KiB/s, done.
Resolving deltas: 100% (5198/5198), done.
Checking connectivity... done.
Go into
pi@raspberrypi-llovet:~ $ cd yowsup
Then
pi@raspberrypi-llovet:~/yowsup $ sudo python setup.py install
. . . {very very large output} . . .
Adding yowsup2 2.5.0 to easy-install.pth file
Installing yowsup-cli script to /usr/local/bin
Installed /usr/local/lib/python2.7/dist-packages/yowsup2-2.5.0-py2.7.egg
Processing dependencies for yowsup2==2.5.0
error: Installed distribution six 1.8.0 conflicts with requirement six>=1.9
Upgrade
pi@raspberrypi-llovet:~/yowsup $ sudo pip install --upgrade six
. . .
Successfully installed six
Cleaning up...
Now all is ok
pi@raspberrypi-llovet:~/yowsup $ sudo python setup.py install
. . .
Using /usr/local/lib/python2.7/dist-packages
Searching for setuptools==5.5.1
Best match: setuptools 5.5.1
Adding setuptools 5.5.1 to easy-install.pth file
Installing easy_install script to /usr/local/bin
Installing easy_install-2.7 script to /usr/local/bin
Using /usr/lib/python2.7/dist-packages
Finished processing dependencies for yowsup2==2.5.0
- sudo pip install yowsup2
From
instructables
and
github
Display yowsup-cli version :
pi@raspberrypi-llovet:/usr/local/bin $ sudo ./yowsup-cli version
yowsup-cli v2.0.15
Using yowsup v2.5.0
Test it :
~/yowsup $ yowsup-cli demos --yowsup --config configfile.txt
sudo yowsup-cli demos --yowsup --help-config {}
In the yowsup directory, create a file called mydetails with the following:
$ nano mydetails
cc=44
phone=447712345678
Now register, this is, get a code via SMS
$ pi@raspberrypi-llovet:/usr/local/bin $ sudo python yowsup-cli registration --config mydetails --requestcode sms
yowsup-cli v2.0.15
yowsup v2.5.0
Copyright (c) 2012-2016 Tarek Galal http://www.openwhatsapp.org
This software is provided free of charge. Copying and redistribution is encouraged.
INFO:yowsup.common.http.warequest:{"status":"sent","length":6,"method":"sms","retry_after":331,"sms_wait":331,"voice_wait":64}
status: sent
retry_after: 331
length: 6
method: sms
You receive a registration code via SMS and use it :
pi@odin:/usr/local/bin $ sudo python yowsup-cli registration --config mydetails --register xxx-xxx
You receive a large text on the screen,
where you have to get the password (as "pw: WFMnm6K0wHmlMsilDMCLq6mHf14=")
and put it in the mydetails file :
cc=34
phone=34333666999
password=jK0zdPJ9zz0M8G3CxmnLqmxuhBk=
Run a demo with
$ yowsup-cli demos --yowsup --config mydetails
/help
----------------------------------------------
/profile setPrivacy [value] [names] Profile privacy. value=all|contacts|none names=profile|status|last.
Names are comma separated, defaults to all.
/profile setPicture <path> Set profile picture
/profile getPrivacy Get profile privacy
/profile setStatus <text> Set status text
/account delete Delete your account
/ib clean <dirtyType> Send clean dirty
/disconnect Disconnect
/help Print this message
/seq Send init seq
/contacts sync <contacts> Sync contacts, contacts should be comma separated phone numbers, with no spaces
/keys get <jids> Get shared keys
/image send <number> <path> [caption] Send an image with optional caption
/presence available Set presence as available
/presence subscribe <contact> Subscribe to contact's presence updates
/presence unsubscribe <contact> Unsubscribe from contact's presence updates
/presence name <name> Set presence name
/presence unavailable Set presence as unavailable
/ping Ping server
/L Quick login
/state paused <jid> Send paused state
/state typing <jid> Send typing state
/contact picture <jid> Get profile picture for contact
/contact picturePreview <jid> Get profile picture preview for contact
/contact lastseen <jid> Get lastseen for contact
/video send <number> <path> [caption] Send a video with optional caption
/groups create <subject> [jids] Create a new group with the specified subject and participants.
Jids are a comma separated list but optional.
/groups list List all groups you belong to
/group info <group_jid> Get group info
/group picture <group_jid> <path> Set group picture
/group invite <group_jid> <jids> Invite to group. Jids are a comma separated list
/group leave <group_jid> Leave a group you belong to
/group setSubject <group_jid> <subject> Change group subject
/group demote <group_jid> <jids> Remove admin of a group. Jids are a comma separated list
/group promote <group_jid> <jids> Promote admin of a group. Jids are a comma separated list
/group kick <group_jid> <jids> Kick from group. Jids are a comma separated list
/login <username> <b64password> Login to WhatsApp
/audio send <number> <path> Send audio file
/message broadcast <numbers> <content> Broadcast message. numbers should comma separated phone numbers
/message send <number> <content> Send message to a friend
/statuses get <contacts> Request contacts statuses
----------------------------------------------
This brings up the Yowsup command line client.
Type /help to see all the available commands.
The [offline] prompt indicates that you aren't connected to the WhatsApp servers.
Use the /L command, which picks up the authentication information from the mydetails file and connects to the server.
The prompt now changes to [connected].
You can now send messages to other WhatsApp users.
To send a message to 34666333999 enter:
/message send 34666333999 "Hola, nen - envio aixo de la Raspberry Pi!"
If the recipient responds with a message, it is displayed on the console on the Raspberry Pi.
To end the session, use the
/disconnect command to quit.
url,
url
Single-Line command
pi@raspberrypi-llovet:/usr/local/bin $ sudo python yowsup-cli demos -c mydetails -s 34638nnnmmm "Hola soc jo"
yowsup-cli v2.0.15
yowsup v2.5.0
Copyright (c) 2012-2016 Tarek Galal
http://www.openwhatsapp.org
This software is provided free of charge. Copying and redistribution is encouraged.
If you appreciate this software and you would like to support future development please consider donating:
http://openwhatsapp.org/yowsup/donate
INFO:yowsup.demos.sendclient.layer:Message sent
Yowsdown
From a Shell
pi@raspberrypi-llovet:~/whatsapp $ cat 1_snd_wassa_msg.sh
# executar amb ./1_snd_wassa_msg.sh
date_name=`date +"%y/%m/%d"`
time_name=`date +"%H:%M"`
ipvariable=$(curl -m 2 -s icanhazip.com);
ipvariable=$(curl -m 2 -s http://checkip.amazonaws.com);
rc1=$?
echo ">>> (2) icanhazip rc ($rc1)"
szOut='('$date_name') ('$time_name') ('$HOSTNAME') ('$0') ('$ipvariable')'
echo 'Pfx is' $szOut
tf_1=34666777888
tf_2=34666778899
tfnum=$tf_1
myID='Hola, soc jo'
missatge="$szOut "+" $myID"
echo 'Lets send to tf ('$tfnum') the message' $missatge
sudo python /usr/local/bin/yowsup-cli demos -c /usr/local/bin/mydetails -s $tfnum "$missatge"
yowsup-cli complete list of flags
pi@raspberrypi-llovet:/usr/local/bin $ pi@raspberrypi-llovet:/usr/local/bin $ sudo python yowsup-cli demos
usage: demos [-h] [-v] [-d] [--help-config] [-l phone:b64password | -c CONFIG]
[-E {android,s40}] [-M] [-y] [-e] [-s phone message]
[-S contacts]
Run a yowsup demo
optional arguments:
-h, --help show this help message and exit
-v, --version Print version info and exit
-d, --debug Show debug messages
--help-config Prints a config file sample
Configuration options for demos:
-l phone:b64password, --login phone:b64password
WhatsApp login credentials, in the format
phonenumber:password, where password is base64
encoded.
-c CONFIG, --config CONFIG
Path to config file containing authentication info.
For more info about config format use --help-config
-E {android,s40}, --env {android,s40}
Set the environment yowsup simulates
-M, --unmoxie Disable E2E Encryption
Command line interface demo:
-y, --yowsup Start the Yowsup command line client
Echo client demo:
-e, --echo Start the Yowsup Echo client
Send client demo:
-s phone message, --send phone message
Send a message to specified phone number, wait for server receipt and exit
Sync contacts:
-S contacts, --sync contacts
Sync ( check valid ) whatsapp contacts
yowsup app debug
yowsup-cli is your friend.
Add in the
--debug
switch and you can see all sent and received stanza data
yowsup-cli RC 1
pi@raspberrypi-llovet:~/semafor $ ./ru0.sh
+++ +++ +++ +++ +++ +++ +++ +++ app SEM starts. Versio [v1.0.l], HN [raspberrypi-llovet], TimeStamp [2016/07/19].
>>> App listening at http://192.168.1.123:1212
20:50:13 Apagar luz (18). (---) Written OFF to pin (18).
20:50:13 Apagar luz (16). (---) Written OFF to pin (16).
20:50:13 Apagar luz (15). (---) Written OFF to pin (15).
>>> Menu enviar msg WhatsApp via python. Tf param is ("666777888").
/home/pi/semafor/1_sem.js:452
if ( err ) throw err ;
^
Error: process exited with code 1
at terminateIfNeeded (/home/pi/semafor/node_modules/python-shell/index.js:100:23)
at ChildProcess.<anonymous> (/home/pi/semafor/node_modules/python-shell/index.js:88:9)
at emitTwo (events.js:100:13)
at ChildProcess.emit (events.js:185:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:204:12)
pi@raspberrypi-llovet:~/semafor $
Issue - solution : split parameters as
args: [ 'demos', '-c', '/usr/local/bin/mydetails', '-s', '34666777888', 'Enviat des NODEJS' ]
Dropdown list with names and phone numbers
code,
JSbin :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo GetSelectOptionData</title>
</head>
<body>
<form name="demoForm">
<select name="demoSelect" onchange="showData()">
<option value="zilch">Select:</option>
<option value="A">Option 1</option>
<option value="B">Option 2</option>
<option value="C">Option 3</option>
</select>
</form>
<p id="firstP"> </p>
<p id="secondP"> </p>
<p id="thirdP"> </p>
<script>
function showData() {
var theSelect = demoForm.demoSelect;
var firstP = document.getElementById('firstP');
var secondP = document.getElementById('secondP');
var thirdP = document.getElementById('thirdP');
firstP.innerHTML = ('This option\'s index number is: ' + theSelect.selectedIndex + ' (Javascript index numbers start at 0)');
secondP.innerHTML = ('Its value is: ' + theSelect[theSelect.selectedIndex].value);
thirdP.innerHTML = ('Its text is: ' + theSelect[theSelect.selectedIndex].text);
}
</script>
</body>
</html>
"blocked" 201701
201701 I get
Authentication Error: not-authorized
When you register the number, you get "bocked"
See
blog
Detailed
discussion
Moving to Telegram
Basic
API, not the
bot
Maybe Signal
Homepage - Google Play + Signal Private Messenger
+1.702.660.4496
3 instaladors
Quina diferencia hi ha entre apt-get, el dpkg i el pip ?
Les eines instalades amb un es veuen des els altres ?
Va a parar tot al mateix lloc ?
- APT i DPKG son cosins germans, apt crida dpkg per sota i haurien de jugar be entre els dos
- El PIP es un repositori de coses python que va "al seu rotllo".
Ara be, algunes coses de pip ja les dona apt. Llavors pip si troba que pot trencar alguna cosa, normalment avisa.
Comanda interessant per reconfigurar :
sudo dpkg-reconfigure postfix
Be, ara podem seguir amb "yum" i "rpm", també "npm".
Veure packages instalats
dpkg -l
Amb el "pip"
pi@odin:~/timer $ sudo pip show pyping
---
Name: pyping
Version: 0.0.5
Location: /usr/local/lib/python2.7/dist-packages
Requires:
Excés de consum
Si alguna vegada conectes coses al USB i el RSPI et fa el tonto, el mes popular és que et demani massa corrent.
Llavors tens el "usb_max_current=1" que el poses a l'arxiu /boot/config.txt,
que és es una mena de carta poker per coses així.
Documentacio.
A mi em passa amb un disc de 1 TB, i a vegades la webcam.
Llegir RPI config.
Al raspbian tens "rpi-config" a la shell per tocar aquestes coses mes facil.
Llegir raspi-config
Permisos
Si en executar "node 1_sem.js" rebem el missatge
>>> App listening at http://192.168.1.123:1212
/home/pi/semafor/1_sem.js:266
if (err) throw err;
^
Error: Pin has not been exported for write
at /home/pi/semafor/node_modules/rpi-gpio/rpi-gpio.js:227:20
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
és que ho hem de engegar des root : sudo node 1_sem.js
Backup de la SD
diyhacking
Trash in /var/log/messages
The /var/log/messages file comes up filled up with
Oct 9 12:14:35 odin rsyslogd-2007: action 'action 17' suspended, next retry is Sun Oct 9 12:16:05 2016 [try http://www.rsyslog.com/e/2007 ]
Fix : comment last lines in /etc/rsyslog.conf
#
daemon.*;mail.*;\
news.err;\
*.=debug;*.=info;\
*.=notice;*.=warn |/dev/xconsole
Restart rsyslog by "sudo service rsyslog restart"
Garbage in /var/log/messages
The /var/log/messages file comes up filled up with
Dec 31 18:58:03 r4 rsyslogd: file '7' write error: No space left on device [v8.1901.0 try https://www.rsyslog.com/e/2027 ]
Here is the problem :
pi@R4:/ $ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/root 27G 13G 14G 49% /
log2ram 40M 40M 0 100% /var/log
Trash in /var/log/daemon.log
File daemon.log gets an entry every 10 seconds, as
Oct 13 19:46:54 odin dhcpcd[448]: wlan0: Router Advertisement from fe80::e241:36ff:febc:bcd1
Put noipv6rs in /etc/dhcpcd.conf
CRDA update log messages
File /var/log/messages has repeated lines as:
Calling CRDA to update world regulatory domain
$ cat messages | grep cfg80211
To remove them, run
sudo apt-get install wireless-regdb iw crda
sudo reboot
Raspall - 20170517
See man crda
Rotate logs manually
With the command
sudo logrotate -d /etc/logrotate.conf
Temperatura de la CPU i la GPU
Per veure la temperatura de la CPU (multiplicada per 1.000) fem servir la comanda :
$ cat /sys/class/thermal/thermal_zone0/temp
To return the temperature of the
SoC as measured by the on-board temperature sensor:
pi@raspberrypi-llovet:~/semafor $ vcgencmd measure_temp
temp=40.6'C ; temperatura de la GPU
Accés des l'exterior
Problema : volem accedir a una IP interna de casa nostra des el exterior
Solució : un port forwarding al teu router a la IP del pi.
El rule seria: src port=8000 dest_port=80 dest_ip=rpi_ip_interna
Llavors des de la biblioteca fas http://ip_externa_del_router:8000
Si volem fer servir noms en lloc de xifres, podem fer servir noip.com o
Duck DNS
JALL (93nnn.nnnn.10304), ll.v.tbasura@gmail.com, 62.57.74.22 (20170517)
SAG Alexandra (93639.8522.10304), bisk.2k9@gmail.com
Volem tenir
192.168.1.123:2415 <-> ip-ext:8815 ; APP "envia foto"
http://myraspiodin.hopto.org:8815
192.168.1.123:1313 <-> ip-ext:7171 ; control all GPIO pins (LED on pin 37)
http://myraspiodin.hopto.org:7171
192.168.1.123:8123 <-> ip-ext:8123 ; APP "temperatura"
http://myraspiodin.hopto.org:8123
192.168.1.123:22 <-> ip-ext:8003 ; acces putty/ssh al "odin" ssh -vv -p 8003 user@myraspiodin.hopto.org
192.168.1.123:1212 <-> ip-ext:9009 ; acces a la APP SEMAFOR / RMTC
192.168.1.123:10000 <-> ip-ext:6666 ; administracio remota del Raspberry "Odin"
192.168.1.46:1245 <-> ip-ext:8000 ; proves acces - \\node\web-server-basico at W500
ESP port forwarding
2424 --- 1144 -- app
3333 --- 22 -- ssh
MTV port forwarding
9000 --- 22 -- ssh u=sebas p=$+.1
HW router
SAG - Timofonica
- fabricant : Comtrend 5813 PN 723306-105 ;
- model : router inalámbrico V2 11n, FTTH ;
- usuari administrador
- administració :
Alejandra [tf]
- verify noip2/DUC works : host myraspiodin.hopto.org
JALL - Vodafone
- model TC-7210,
manual
- default IP = 192.168.0.1
- U = "blank", P = "admin"
- SSID (2,4 GHz) = "ONO1241", SSID (5 GHz) = "ONO1241-5G"
[/]
Problemes :
- no puc llegir IP externa - solucio : DNS de Google
- no puc enviar email - solucio : DNS
pi@raspall:~ $ curl -m 2 -s icanhazip.com // curl -m 2 -s http://checkip.amazonaws.com
62.57.74.22
pi@raspall:~ $ date
Tue May 16 18:01:05 CEST 2017
pi@raspall:~ $ cat /etc/resolv.conf
# Generated by resolvconf
nameserver 8.8.8.8,
nameserver 8.8.4.4
Msg ID is (12).
RASPALL-001 (17/05/16) (18:04) (raspall) (./snd_1.sh) (62.57.74.22).
pi@raspall:/usr/local/etc $ host raspall.hopto.org
raspall.hopto.org has address 62.57.74.22
curl 192.168.0.123:1212
curl 62.57.74.22:9007
hostname
- "sudo vi /etc/hosts" : at 127.0.0.1
- "sudo vi /etc/hostname"
- reboot
run at startup
Edit /etc/rc.local and use absolute paths :
date_name=`date +"Y%y/M%m/D%d"`
time_name=`date +"h%H:m%M"`
echo "(" $date_name "-" $time_name ") RC.LOCAL" >> /home/pi/logs/RC.LOCAL.log
# "append output (stdout, file descriptor 1) onto file.txt and send stderr (file descriptor 2) to the same place as fd1"
sudo /usr/bin/node /home/pi/semafor/1_sem.js >> /home/pi/logs/sem.log 2>&1 &
Power off
Hi ha una manera de dir-li que passa amb els ports quan s'apaga el pi.
Crec que als "DTB" (Device tree)
Remote Desktop
For
remote access,
I use
VNC.
Enable VNC graphically :
- on your Raspberry Pi, boot into the desktop
- select Menu > Preferences > Raspberry Pi Configuration > Interfaces
- ensure VNC is Enabled
Sadly, my display does not have VNC - it only shows :
*) camera
*) SSH (*** enabled ***)
*) SPI
*) I2C
*) Serial
*) 1-wire
*) remote GPIO
Enable VNC from command line
Do
$ sudo raspi-config
Now, enable VNC Server by :
- navigate to "7 - Advanced Options"
- scroll down and select "A0 - Update"
- scroll down and select "A5 - VNC > Yes"
Verify VNC server is running :
$ sudo
XRDP
XRDP is a Linux implementation of the Windows Remote Desktop Server / Terminal Server.
sudo apt-get install xrdp
sudo reboot
Display its status :
pi@odin:~ $ /etc/init.d/xrdp status
â xrdp.service - LSB: Start xrdp and sesman daemons
Loaded: loaded (/etc/init.d/xrdp)
Active: active (running) since Sun 2016-10-23 09:37:30 CEST; 7min ago
Process: 548 ExecStart=/etc/init.d/xrdp start (code=exited, status=0/SUCCESS)
CGroup: /system.slice/xrdp.service
ââ641 /usr/sbin/xrdp
ââ645 /usr/sbin/xrdp-sesman
Open firewall :
sudo nano /etc/iptables.firewall.rules {sag - no such file}
Add this following line: "-A INPUT -p tcp --dport 3389 -j ACCEPT"
Save using "CTRL-W"
As we have it in ODIN, if we start Remote Desktop, we have
The log lines are :
- connecting to sesman ip 127.0.0.1 port 3350
- sesman connect ok
- sending login information to session manager, please wait
- xrdp_mm_process_login_response: login successful for display ...
- connecting to 127.0.0.1 5910
- tcp connected
- security level is 2 (1 = none, 2 = standard)
- password ok
- sending share flag
- receiving server init
- receiving pixel format
- receiving name length
- receiving name
- sending pixel format
- sending encodings
- sending framebuffer update request
- sending cursor
- connection complete, connected ok
Tired of "sudo" ?
Become "root" for the rest of the session :
sudo su -
ping: icmp open socket: Operation not permitted
I get (20191228)
pi@odin:~ $ ping 8.8.8.8
ping: icmp open socket: Operation not permitted
pi@odin:~ $ which ping
/bin/ping
pi@odin:~ $ ls -al /bin/ping
-rwxr-xr-x 1 root root 38844 Feb 12 2014 /bin/ping
pi@odin:~ $ sudo chmod u+s /bin/ping ; set user on execution = root -> make it world executable
pi@odin:~ $ ls -al /bin/ping
-rwsr-xr-x 1 root root 38844 Feb 12 2014 /bin/ping
WatchDog
Per monitoritzar que tot va be (i pescar la causa si cau), posem una tasca cada 15 minuts :
wd - feina a fer
pi@odin:~/eines $ cat cron_feina_15_min.sh
#!/bin/bash
fnLog="/home/pi/logs/cron_job.log"
echo "======= /home/pi/eines/cron_feina_15_min.sh === ($0) ======" >> $fnLog
echo "Deit" >> $fnLog
date >> $fnLog 2>&1
echo "Display filesystem amb DF -H" >> $fnLog
/bin/df -h >> $fnLog 2>&1
echo "Display temperature amb VCGENCMD" >> $fnLog
/usr/bin/vcgencmd measure_temp >> $fnLog 2>&1
echo "wifi name using /sbin/iwgetid" >> $fnLog
/sbin/iwgetid >> $fnLog 2>&1
echo "wifi config using /sbin/iwconfig" >> $fnLog
/sbin/iwconfig >> $fnLog 2>&1
echo "IP externa ODIN via CURL ICANHAZIP" >> $fnLog
curl -m 2 -s icanhazip.com >> $fnLog 2>&1
echo "IP externa ODIN via CURL CHECKIP.AMAZONAWS" >> $fnLog
curl -m 2 -s http://checkip.amazonaws.com >> $fnLog 2>&1
echo "IP externa ODIN via HOST NOIP2" >> $fnLog
host myraspiodin.hopto.org >> $fnLog 2>&1
echo "IP externa RASPALL via HOST NOIP2" >> $fnLog
host raspall.hopto.org >> $fnLog 2>&1
exit 0
wd - programacio
Use "crontab -e" under "root" user :
# m h dom mon dow command
0 4 * * * /home/pi/eines/cron_feina_send_email.sh
*/15 * * * * /home/pi/eines/cron_feina_15_min.sh
Use "crontab -l" to list active crontab for actual user, or sudo crontab -l to display "root's" crontab
wd - activacio
$ sudo /etc/init.d/cron restart
Lo RSPI3 de Lo Pere
Pere's sw :
- el client de torrent és transmission - lightweight BitTorrent client
- el servidor de DLNA és minidlna
- NAS server - USB driver with external power
- nginx - HTTP server, mail proxy server, TCP/UDP proxy server,
- fav.casacam.net - 95.23.38.212 [20190214]
Install software using "Menu" + "Preferences" + "Add Software"
Verify it by
dpkg -l | grep transmission
Transmission
Use GUI (client + command line + common files + daemon, 2.84-0.2)
or
cmd line :
sudo apt-get update - update system often
sudo apt-get install transmission-daemon
mkdir -p /media/NASDRIVE/Torrent_inprogress
mkdir -p /media/NASDRIVE/Torrent_complet
sudo usermod -a -G pi debian-transmission - add debian-transmission user to pi group
sudo vi /etc/transmission-daemon/settings.json -
"rpc-authentication-required": false,
"rpc-whitelist": "127.0.0.1,10.0.1.*",
sudo service transmission-daemon reload
http://your_raspberry_pi_IP:9091 - http://192.168.1.123:9091/transmission/web/ = web interface
nodejs and GPIO
$ cat gpio.js
var gpio = require( 'rpi-gpio' ) ;
if ( process.argv.length < 4 ) return console.error( 'Usage : node gpio pin# ON|OFF' ) ;
let pin = process.argv[ 2 ] ;
let onoff = /^(on|true)$/i.test( process.argv[ 3 ] ) ;
gpio.write( pin, onoff, function( err ) {
if ( err ) return console.error( err ) ;
console.log( "Pin #${pin} turned ${onoff}" ) ;
} ) ;
Lo RSPI3 den ESP
20190207 - NexusPalma, c Arago 24, 971 91 45 70 -
portal -
80 € (tarja, caixa, alimentador, cable HDMI i tarja SD)
Totes les experiencies al blog
Compte amb el "sudoers is world writable"
Send email with IP
Primera versio :
sebas@henry:~/nodes $ cat /etc/cron.hourly/enviaip -> /home/enric/sh-enric/ip.sh
#!/bin/bash
myLog="/home/enric/logs/ip.log"
szHORA=$(date)
echo "$szHORA--- Hola - program name ($0)" >> $myLog
szIPexterna=$(curl -m 2 -s icanhazip.com)
szIPexterna=$(curl -m 2 -s http://checkip.amazonaws.com)
rv=$?
echo "CURL return code ("$rv")" >> $myLog
szIPinterna="$(/sbin/ifconfig wlan0 | grep 'inet 192' | cut -d: -f2 | awk '{ print $2}')"
szIPs="Today IPs : external {$zIPexterna}, internal {$szIPinterna}."
echo "($HOSTNAME) ($0) --- ($szHORA) --- ($szIPs)" | mail -s "($szHORA) my IPs" henrybrossa@gmail.com
rv=$?
echo "MAIL return code ("$rv")" >> $myLog
exit 0
llegir la nostra IP
Nomes a Raspbian :
from subprocess import check_output
print check_output(['hostname', '-I'])
llegir la temperatura
Un classic :
sebas@henry:~ $ cat /home/sebas/python/esp_mostrar_temperatura.py
temp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3
tempgpu = check_output(["vcgencmd","measure_temp"]).decode()
print( '[' + szTime + '] temp.CPU => ' + str(temp) + ', temp.GPU => ' + str(tempgpu) )
Compte : si no volem "VCHI initialization failed", hem de engegar amb "sudo ./esp_mostrar_temperatura.py" o fer "sudo usermod -aG video sebas"
sebas@henry:~/python $ sudo ./esp_mostrar_temperatura.py
[2020-11-05 21:04:15 ] temp.CPU => 52.078, temp.GPU => temp=52.6'C
web server minim
Primera versio :
sebas@henry:~/nodes $ cat wsm.js
var http = require('http') ; // cargar el modulo HTTP
function onRequest(request, response) { // configurar una respuesta HTTP para todas las peticiones
console.log( "Peticion Recibida." ) ;
response.writeHead( 200, { "Content-Type": "text/html" } ) ;
response.write( "*** Hola Mundo ***" ) ;
response.end() ;
} ;
var server = http.createServer(onRequest) ;
server.listen(1144) ; // escuchar en el puerto 1144
console.log( "Servidor WSM.JS escoltant a http://localhost:1144/" ) ; // poner un mensaje en la consola
web server amb express i js al client
See it
Enviar per email un tgz dels fitxers importants
Aquest es qui fa la feina :
sebas@henry:~/eines/backup_by_mail $ cat fer_backup.sh
#
#
#
#!/bin/bash
# Passos del algorisme :
# 1 - esborrem el fitxer tgz anterior
# 2 - comprimim els fitxers en el tgz
# 3 - enviem el tgz per email
# ---
# Versions :
# 1.a 20190327 - enviem a yandex
# 1.b - esborrem contingut directori abans de tot
# 1.c - comptar el nombre de fitxers copiats
# 1.d - millorar missatges, SAG 20191015
# 1.e - 2 destinataris
# 1.f - copia de ESP a MARS i adaptacio directoris, destinataris, ...
# 1.g - filtre mail.log
# 1.h - adaptacio ODIN
# 1.i - canviar nom a JPEG
# 2.a - dont copy files to keep directory, use MUTT, use TINET gateway
# 2.b - verify file exists
# 2.c - trace job start
# 2.d - proper date format
# 3.a - add CRON programation
#
# Debug
# ping gmail-smtp-in.l.google.com
# ping mx.yandex.ru
#
# error 2020 : May 5 14:22:20 odin sSMTP[2572]: 552 5.7.0 message content and attachment content guidelines. h10sm3014356wrv.29 - gsmtp
# entrar per t1net -
cfg
#
szVer="v 3.a"
myPath="/home/sebas/eines/backup"
myCronFile=$myPath"/cron_values.txt"
fnIN=$myPath"/llista_fitxers.txt"
fnOUT=$myPath"/sortida.tar"
if [[ ! -f $fnIN ]]
then
echo "--- $fnIN does not exist on your filesystem."
exit 1
fi
fnLOG="/home/sebas/logs/fer_backup.log"
szHN=$HOSTNAME
fn2Send="pic_"$szHN"_tar.jpg"
szDESTI="manel.carnero@yandex.com sveta@gmx.com"
szT=$(date +%R)
szD=$(date +"%d/%m/%Y") # short date, 4 digit year, day before month
szDeit=$szD,$szT
szCOS="+++ $szDeit +++ ($szHN) +++ ($0) +++ ($szVer) +++ Backup files from ($fnIN) sent to ($szDESTI)."
echo -e "\n$szCOS" >> $fnLOG
echo "(0) --- create $myCronFile" >> $fnLOG
echo "+++ ($szDeit) +++ cron values +++" > $myCronFile
crontab -l >> $myCronFile
ls -al /etc/cron.daily/ >> $myCronFile
ls -al /etc/cron.hourly >> $myCronFile
ls -al /etc/cron.monthly/ >> $myCronFile
ls -al /etc/cron.weekly/ >> $myCronFile
echo "(1) --- esborrar fitxers vells" >> $fnLOG
rm -f $fnOUT >> $fnLOG 2>&1
rm -f $fn2Send >> $fnLOG 2>&1
echo "(2) --- TAR fitxers nous" >> $fnLOG
cnt=0
while read linia; do
echo "+++ Posem fitxer" $linia >> $fnLOG
if [ -f "$linia" ]; then
cnt=$(($cnt+1))
echo "+++ ($cnt) +++ $linia exists" >> $fnLOG
tar -rf $fnOUT $linia >> $fnLOG 2>&1
else
echo "--- $linia does not exist" >> $fnLOG
fi
done < $fnIN
echo "(3) --- rename de ($fnOUT) a ($fn2Send)" >> $fnLOG
mv $fnOUT $fn2Send
szSubject="+++ $szDeit +++ ($szHN) +++ ($0) +++ ($szVer) +++ Backup ($cnt) files from ($fnIN)."
echo "(4) --- subject ($szSubject)" >> $fnLOG
szBody="* $szDeit * [$szHN] * ($0) sends ($cnt) files using mutt *"
echo "(5) --- body ($szBody)" >> $fnLOG
echo "(6) --- enviem fitxer ($fn2Send) a ($szDESTI)" >> $fnLOG
# normal mutt
echo "$szBody" | mutt -s "$szSubject" -a "$fn2Send" -- $szDESTI
# debug mutt : see ~/.muttdebug0
# echo "$szBody" | mutt -d 5 -s "$szSubject" -a "$fn2Send" -- $szDESTI
rv=$?
echo "$szDeit MAIL return code" $rv >> $fnLOG
# szFiltre="tinet.cat"
# echo "$szDeit Que hi ha de ($szFiltre) al LOG de MAIL :" >> $fnLOG
# cat /var/log/mail.log | grep $szFiltre >> $fnLOG
# tail -n 30 /var/log/mail.log | grep "yandex.com" >> $fnLOG
exit 0
La llista de fitxers importants es : (see email_mutt_fa_backup)
$ cat llista_fitxers.txt
/boot/config.txt
/boot/firmware/config.txt
/etc/apt/sources.list
/etc/Muttrc
/etc/motd
/etc/rc.local
/home/pi/.bash_aliases
/home/pi/eines/backup/cron_values.txt
/usr/local/bin/odin_restart
/usr/local/bin/motd
I aixi fem que es repeteix periodicament :
sebas@henry:/etc/cron.daily $ sudo ln -s /home/sebas/eines/backup_by_mail/fer_backup.sh enviar_tgz_a_yandex
Compte : fer_backup.sh ha de tenir chmode 755
Compte : cron corre sota usuari "root" i no sap trobar on posar el TGZ ni on fer el log ! See cron with explicit paths
Netejar els logs del usuari
- fem un shell
- l'engeguem un cop a la setmana
shell per netejar els logs
sag@odin:~ $ cat /home/sag/eines/crear_logs.sh
#!/bin/bash
oFN="/home/sag/logs/rmtc.log"
echo "*** [`date -R`] ($0) /Raspberry-Pi-Simple-Web-GPIO-GUI/app.js ***" > $oFN
oFN="/home/sag/logs/photo_server.log"
echo "*** [`date -R`] ($0) /express-sendfile/serverapp.js ***" > $oFN
exit 0
comanda per engegar la neteja un cop per setmana
sag@odin:~ $ cd /etc/cron.weekly/
sag@odin:/etc/cron.weekly $ sudo ln -s /home/sag/eines/crear_logs.sh crear_logs_buids
Toquem ferralla
- compro cable expansio GPIO a AliBaba
- compro "Modul Board groc 550 contactes", 150x 50 = 10x 47 + 2x 40, 12 €, 20190320 Diotronic
- compro SSR CX240D5, 12 €
"deures" o feina que pots fer
- (1-henry) engegar wsm.js quan engegi la maquina
- (henry) fer que wsm.js envii la hora en la resposta
- (henry) fer que wsm.js envii una mica de HTML,
com un fons de color, un titol i un font gran per veure el texte millor
- (henry) wsm.js amb respostes personalitzades :
- http://localhost:1414/enric -> "Hola, Enric"
- http://localhost:1414/sebas -> "Hola, Sebas"
- (gmail) fer un filtre a gmail que posi els missatges provinents de "henry" en una carpeta "msg-de-henry"
- (2-henry) des de wsm.js, cridar a un python que em digui la versió del python en picar http://localhost:1414/python
- (mac/henry) fer un python que llegeixi el correu de henrybrossa/msg-de-henry
mitjançant imaplib
- (nexus) aconseguir una webcam barata (menys de 5 eurus)
- (3-henry) fer un python que faci una foto amb una webcam mitjançant OpenCV
- (henry) amb node fet foto i mostrar la foto en rebre http://localhost:1414/phyton_photo
- (henry) aprendre a fer anar el VI - editor des command line (o VIM, amb mes colors)
- (mac) aprendre a fer anar el PUTTY - client SSH
- (henry) fer servir webmin per configurar el Linux -
url,
pimylifeup,
url (es)
- (henry) esbrinar com funciona "motd" (usuari "sebas") - fes "which motd" (compte que no es /etc/motd, que és un fitxer de texte)
- (4-henry) posar el node.js a la darrera versio, incloent nova font de packages
- crear un compte a yandex.com, on enviarem un 7z dels fitxers importants (10 GB on Yandex.Disk)
- (henry) salvar el teu codi a github i omplir README.md
- (henry) instalar noIP per accedir des l'exterior per nom i no per ip
- (henry) esborrar /var/log/*.gz un cop a la setmana a la 1 de la matinada de dilluns a dimarts
- (5-henry) engegar node com a servei de Linux
- (wsm) posar una pagina de "Ajuda" del WSM, on surti
- la data i hora actuals
- com es diu el host
- la seva IP, interna i externa
- el nom del programa i el directori actual
- directori i fitxer on desa el log del seu funcionament
podem mostrar els darrers 20 esdeveniments ?
- qui l'ha fet i el seu email (yandex ?)
- amb quines eines
- URLs de les pagines que has fet servir per aprendre
- on es el projecte al github
- enviar contingut de "llista_fitxers.txt" a "enricsarra@yandex.com" mitjançant "fer_backup.sh"
- en una APP nodejs, rebre un requeriment i intentar esbrinar la IP del client de on ve el requeriment
- (20200806) engegar un bot de Telegram per a que el Raspberry respongui a missatges enviats des el telefon
(1) Engegar WSM.JS en engegar la maquina
Curios entorn - jo conec "/etc/rc.local" :
enric@henry:~/sh-enric $ crontab -e
# ----------- Arrancar servidor wsm del sebas
@reboot /home/enric/sh-enric/wsm.sh
Better dont use @reboot
On la comanda que engeguem és :
$ cat /home/enric/sh-enric/wsm.sh
#!/bin/bash -e
# set log file name
myLog=/home/enric/logs/start_wsm.log
# set output string
szTxt="( [`date -R`] ) +++ +++ Engego WSM.JS +++ log($myLog) +++"
# write to /var/log/syslog
logger -i -p user.info $szTxt
# start node APP and trace events
/bin/node /home/sebas/nodes/wsm.js >> $myLog
(2) Llistar emails des python
sebas@henry:~/eines/python/llegir_emails $ cat busca.sh
#!/bin/bash
szEmail="henrybrossa@gmail.com"
szClau="la-teva-clau-de-pas"
szBustia="inbox"
if [ $# -ge 1 ]; then
szEmail=$1
fi
if [ $# -ge 2 ]; then
szClau=$2
fi
if [ $# -ge 3 ]; then
szEmail=$3
fi
echo -e "email \t" $szEmail
echo -e "pwd \t" $szClau
echo -e "bustia \t" $szBustia
./imap.py $szEmail $szClau $szBustia
rv=$?
echo ">>> rc imap = ($rv)."
exit 0
(3) Fer foto des python
/home/sag/express-sendfile/fer_foto.py
(4) Posar node.js a la darrera versio
$ sudo apt full-upgrade -y
$ curl -sL https://deb.nodesource.com/setup_11.x | sudo -E bash -
$ apt-get install nodejs -y
(5) engegar node com a servei de Linux
We shall use upstart daemon
- create "miAplicacion.conf" in "/etc/init" with
start on runlevel [2345]
stop on runlevel [!2345]
respawn
respawn limit 10 5 ; not more than 5 times in 10 secs
setuid ubuntu ; not root, please
chdir /opt/myAplicacion ; where is the code
env PORT=3000 ; set envir vars
exec npm start ; use package.json !
- run command "service miAplicacion start"
Carlos Azaustre (old)
Molt millor
així amb
systemd :
- create myapp.service :
[Unit]
Description=My app
After=network.target
[Service]
ExecStart=/var/www/myapp/app.js
Restart=always
User=nobody
# Note Debian/Ubuntu uses 'nogroup', RHEL/Fedora uses 'nobody'
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/var/www/myapp
[Install]
WantedBy=multi-user.target
- "/var/www/myapp/app.js" should have "#!/usr/bin/env node" on the very first line
- you want the file to be executable: "chmod +x app.js"
- copy your service file into the "/etc/systemd/system"
- start it with "systemctl start myapp"
- make systemd aware of the new service: "sudo systemctl daemon-reload"
- enable it to run on boot with "systemctl enable myapp"
- see logs with "journalctl -u myapp"
A/D conversion in Rspi
Per convertir un senyal analògic en una dada digital farem menester un conversor A/D "MCP3008" :
Communication with the MCP3004/3008 devices is accomplished
using a standard SPI-compatible serial interface
-
wiki
SPI on Rspi
SPI requires 4 pins :
SCLK | ---> | SCLK Serial Clock
SPI MOSI | ---> | MOSI SPI Master Out Slave In
master MISO | <--- | MISO slave
SS/ | ---> | SS/ Slave Select
| |
The pins are :
pin gpio name
19 GPIO10 SPI0_MOSI
21 GPIO9 SPI0_MISO
23 GPIO11 SPI0_SCLK
24 GPIO8 SPI CE0_N (optional if only one device on bus)
26 GPIO7 SPI CE1_N
26 ground
docu
Config SPI and install SPIDEV
raspi-config ; allow SPI and enable it at startup
sudo apt-get update ; sovint
sudo apt-get upgrade ; delicat
sudo apt-get install python-pip python-dev
sudo pip install spidev
Python access to SPI
Some python code :
#!/usr/bin/python
#--------------------------------------
# This script reads data from a
# MCP3008 ADC device using the SPI bus.
#
# Analogue joystick version!
#
# Author : Matt Hawkins
# Date : 17/04/2014
#
# http://www.raspberrypi-spy.co.uk/
#
#--------------------------------------
import spidev
import time
import os
# Open SPI bus
spi = spidev.SpiDev()
spi.open(0,0)
# Function to read SPI data from MCP3008 chip
# Channel must be an integer 0-7
def ReadChannel(channel):
spi.max_speed_hz = 1350000
adc = spi.xfer2([1,(8+channel)<<4,0])
print( "raw data", adc)
data = ((adc[1]&3) << 8) + adc[2]
return data
# Define sensor channels
# (channels 3 to 7 unused)
swt_channel = 0
vrx_channel = 1
vry_channel = 2
# Define delay between readings (s)
delay = 0.5
while True:
# Read the joystick position data
vrx_pos = ReadChannel(vrx_channel)
vry_pos = ReadChannel(vry_channel)
# Read switch state
swt_val = ReadChannel(swt_channel)
# Print out results
print "--------------------------------------------"
print("X : {} Y : {} Switch : {}".format(vrx_pos,vry_pos,swt_val))
# Wait before repeating loop
time.sleep(delay)
url
A/D links
motion
Homepage
Motion can connect to a network camera through a normal TCP socket.
All you need to give it is the URL.
The URL given must return either one single jpeg picture or an mjpeg stream.
For the time being Motion cannot connect to a video stream such a mpeg, mpeg4, divx.
The URL must return one single jpeg image or an mjpeg stream! You can connect through a proxy server.
"sudo apt-get install motion", conectes la usb webcam i reboot -
recepta
FireFox
If we want to use Firefox to access sqlite,
we have to install it from "Add/remove software" + "Mozilla Firefox ESR"
Raspberry 4
Compare 3B+ and 4
Tech specs Raspberry Pi 4 :
- USB-C power supply (minimum 3A, 15W)
- 2x micro HDMI ports
- 64-bit CPU Broadcom BCM2711, Quad core Cortex-A72 (ARM v8) @ 1,5 GHz
- SDRAM : 1 GB, 2 GB, 4 GB LPDDR4-2400
- 2x USB 3.0 ports, 2x USB 2.0 ports
- Gigabit Ethernet
- 2.4 GHz and 5.0 GHz IEEE 802.11ac wireless
- Bluetooth 5.0, BLE
- H.265 (HEVC) hardware decode (up to 4Kp60)
- H.264 hardware decode (up to 1080p60)
- VideoCore VI 3D Graphics
- supports dual HDMI display output up to 4Kp60
- Pi4B requires a good quality USB-C power supply capable of delivering 5V at 3A.
If attached downstream USB devices consume less than 500mA, a 5V, 2.5A supply may be used
nice pdf
More specific :
- CPU : Broadcom BCM2711, quad-core de 64 bits ARM Cortex A71 a 1,5 Ghz
- GPU : VideoCore VI 500 MHz
- RAM : 4 GB de LPDDR4-2400 SDRAM
- USB : 2x USB 3.0, 2x USB 2.0
- video y sonido : 2x micro HDMI
- H.265 : soporte hasta 4Kp60
- conectividad : WiFi 2,4 GHz / 5 GHz, IEE 802.11.b/g/n/ac, Bluetooth 5.0, BLE
- power supply : 5V 3A USB-C
Kubii :
1 GB = 38 €, 2 GB 49 €,
amason, 62 €, 4 GB RAM
Use the new Buster,
the latest version of Debian Linux
As it has USB 3, we can use a SSD disk !
Raspberry 4 improvements
Que afegeix el Raspberry 4 ?
diferencies :
- bluetooth 5
- USB 3.0 - es important si tens un disk extern gros, es veritat
- 4 GB de RAM - si et cal doncs ja ho tens
- true Gigabit Ethernet
- support for duall 4K output
Raspberry 4 CPU info
sebas@r4:~ $ cat /proc/cpuinfo
processor : 0-1-2-3
model name : ARMv7 Processor rev 3 (v7l)
BogoMIPS : 108.00
Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xd08
CPU revision : 3
Hardware : BCM2711
Revision : c03112
Serial : 10000000b8e2879d
Model : Raspberry Pi 4 Model B Rev 1.2
system info
Raspberry 4 CPU BCM2711 RESET registers
BCN27xx imagebuilder
Raspberry 4 to-buy list
You will need
- a 15W USB-C power supply – we recommend the official Raspberry Pi USB-C Power Supply
- a microSD card loaded with NOOBS, the software that installs the operating system
- a keyboard and mouse
- cables to connect to one or two displays via Raspberry Pi 4's micro HDMI ports
Kubii :
- placa : 39 € (RAM 2 GB), 61 € (RAM 4 GB)
- power supply : 9 €
- uUSB to USB-C adapter : 1 €
- caixa : sense ventilador 6 €
- cable uHDMI a HDMI : 6 €
- tarja micro SD : 16 GB o 32 GB
Per peces, a Amason :
- la caixa, alimentador i cables (21 €)
url
- 2) la placa amb 4 GB de RAM (63 €)
url
- 3) tarja SD de 64 GB (18 €)
url
Raspberry 4 MTV
20200503 : amason, 120 €,
tech details
MTV email at tinet,
espai web (sense la "i" ?)
deures per en MTV amb la Raspberry 4
- fer servir .bash_aliases : alias l='ls -als --color=auto'
- posar un alias per la R4 al /etc/hosts del Ubuntu ( i pel PiZero )
- shell que s'executa quan engega la maquina i afegeix la data actual a /home/miquel/logs/engegades.log
- instalar webmin
- enviar cada hora un email a Tinet amb la IP externa del router i la ocupacio de disc (i la temperatura de la GPU)
- posar algo de HTML "maco" a les pagines de Tinet : inici
- fer que el "prompt" del Ubuntu sigui de un color diferent del del R4 - aixi el ssh es veura diferent
- fer un python que escrigui en un fitxer de texte diversa informacio de la maquina :
- hora i data actual
- hostname
- IP interna i externa
- nom de la wifi a la que esta conectat
- RAM instalada a la maquina
- CPU instalada a la maquina
- disc instalat a la maquina i espai lliure restant
- repositoris actuals de Ubuntu
- configuracio de email / mutt
- tasques programades
- fer un python que envii un fitxer a Tinet - vull veure la meva IP externa a
IP_R4.HTM !
- tenir clar quins ports hi ha oberts al router i a quin ip:port internes estan mapejats
- clicar en una icona del portatil amb Ubuntu i que s'obri una finestra que mostri continuament la temperatura de la CPU i GPU del Raspberry 4
- posar un TC74 al bus i2c del R4-9 i mostrar la temperatura al mon : as R3 ,
using github
feina en engegar el R4
Fem servir un servei del tipus "systemd" :
- la definicio del perfil del servei s'ha de ubicar al directori /home/<usuari>/.config/systemd/user/
i s'ha de dir <nom servei>.service :
~$ vi /home/miquel/.config/systemd/user/r4_start.service
[Unit]
Description=Servei de engegada del R4 (v 1.a)
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
Restart=no
WorkingDirectory=/home/miquel/eines
ExecStart=/home/miquel/eines/r4_start_job.sh
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=r4_start
# User=miquel --- "user" services require this sentence not to be present ---
Environment=NODE_ENV=production
[Install]
WantedBy=default.target
Aquesta definicio te molts parametres - veure documentacio
service
i
unit ,
man pages
- el codi que fa la "feina" s'ha definit a la sentencia ExecStart - editem /home/miquel/eines/r4_start_job.sh
~$ vi /home/miquel/eines/r4_start_job.sh
#!/bin/sh
date >> /home/miquel/logs/engegades.log
exit 0
- aquest log ha de existir :
~$ touch /home/miquel/logs/engegades.log
- el servei s'activa aixi :
~pi@raspberrypi:~ $ systemctl --user enable r4_start.service
Created symlink /home/pi/.config/systemd/user/default.target.wants/r4_start.service → /home/pi/.config/systemd/user/r4_start.service.
- el servei s'ha de llistar aixi
~$ systemctl --user cat r4_start.service
- provem de engegar-lo a veure si no te cap problema (normalment de permisos) :
~$ sudo systemctl start r4_start
- si tenim algun problema, tenim 2 eines complementaries :
~$ sudo systemctl status r4_start
~$ sudo journalctl -xe
Ara, cada cop que s'engegui la maquina, tindrem una linia dins eixe fitxer de log - /home/miquel/logs/engegades.log
Una "feina" mes sofisticada pot ser :
~$ cat /home/miquel/eines/r4_start_job.sh
#!/bin/bash
myLog="/home/miquel/logs/engegades.log"
date_name=`date +"Y%y/M%m/D%d"`
time_name=`date +"h%H:m%M"`
szTs="[$HOSTNAME] $date_name - $time_name"
szId="+++ +++ +++ ($szTs) ($0) from /home/miquel/eines/r4_start.sh"
# timestamp system start at own log file
echo "$szId" >> $myLog
# trace in /var/log/syslog
logger -i -p user.info $szId
exit 0
1-er projecte de'n Miquel : control del ventilador del R4
Descripció : volem mesurar la temperatura del TC74 o de la CPU cada 10 o 15 segons.
Amb aquest valor aturarem o engegarem el ventilador conectat a un pin GPIO.
Com que la majoria del temps el programa estarà inactiu, no fem un servei "systemd" sino que el manegarem via crontab.
Això té com a mínim un inconvenient sobre la opció de "sleep()" dins el python - el codi no te "memoria" del que ha passat abans,
a menys que ho posem en un fitxer.
Farem servir nomes python, vist que sabem llegir del TC74 i de la CPU i també manegar pins del GPIO.
Codi que ja tenim :
(a) feina del manegador del ventilador del R4
~$ cat /home/miquel/python/ventilador/feina.py
#!/usr/bin/env python
# 0 - ficar una entrada al log
# 1 - llegir la temperatura
# 2 - decidir que fer amb el ventilador
# el log es defineix al crontab (/home/miquel/logs/ventilador.log)
import datetime
import platform #
doc
import sys
# print( "Python version", sys.version )
print( 'Pyhton version', platform.python_version() )
# (0) trassa
now = datetime.datetime.now()
szInici = now.strftime("%Y-%m-%d %H:%M:%S")
print( '*** ' + szInici + ' *** anem a llegir la temparatura al TC74 *** ' )
# (1)
# (2)
sys.exit()
(b) crontab del manegador del ventilador del R4
Si volem que s'executi el programa python cada 15 minuts, codifiquem
~$ cat /home/miquel/python/ventilador/cron_ventilador.txt
##########################################################
# minute (0-59), #
# | hora (0-23), #
# | | dia del mes (1-31), #
# | | | mes (1-12), #
# | | | | dia de la semana (1-7 donde 1=Lunes) #
# | | | | | comandos #
##########################################################
*/15 * * * * /home/miquel/python/ventilador/feina.py >> /home/miquel/logs/ventilador.log 2>&1
... i ho posem en funcionament amb la comanda :
~$ crontab -u sebas cron_ventilador.txt
Finalment comprovem que ha engegat be amb :
~$ crontab -l
la xarxa d'en Miquel
.-----------------------.
| | 8000 -> R0:22 9000 -> R0:900
| router Movistar | 8004 -> R4:22 9004 -> R4:904
| 192.168.1.1 |
| DHCP server [33.199] |---.
| | |
.-----------------------. |
|
| .-------------------------.
| | |
| | R4-9 |
.----. eth0 |
| | 192.168.1.219/24 (fixe) |
| | |
| .-------------------------.
|
| .--------------------------.
| | |
| | PI-0-Eli |
.----. wlan0 |
| | 192.168.1.220/24 (fixe) |
| | |
| .--------------------------.
|
| .--------------------------.
| | |
| | T410 Ubuntu |
.----. wlan0 |
| | 192.168.1.210/24 (fixe) |
| | |
| .--------------------------.
|
| .--------------------------.
| | |
| | Air-Elisenda |
.----. wlan0 |
| | 192.168.1.40/24 (DHCP) |
| | |
| .--------------------------.
|
| .-------------------------.
| | |
| | R4-1 (per reparar) |
.----. eth0 |
| | 192.168.1.70/24 (fixe) |
| | |
| .-------------------------.
|
|
.--- ( ARRIS, 192.168.200 )
|
|
Periferics d'en MTV
Comencem (20200615) amb un TC74 i despres ja veurem ...
Altres :
- MCP3421, 18-bit ADC converter,
specs
- i2c eeprom 24AA256/24FC256/24LC256,
specs
- mcp9800 (sensor de temperatura),
- MCP3221 (12 bit ADC),
- TC1321 (DAC 10 bits),
- MCP23008 8 bit I/O expander,
- SPI 25LC020,
- TC77 (sensor temperatura), encapsulat TO220
- MCP3201 (ADC),
- MCP1010 (potenciometre digital),
- MCP6032 (PGA),
- et deixaré per tu una 25LC256 i una plaqueta amb un MCP3421 (Delta Sigma ADC)
- 20200628 :
- OLED Display I2C 128 x 64 pixeles 0.96" , 6.8 €
consiste en 128x64 píxeles OLED, controlados individualmente por el chip SSD1306
- 20200628 : OLED Display I2C 128 x 32 pixeles 0,91" , 7 €
Para facilitar su programación, se encuentran varias librerías disponibles en línea que se puede utilizar para el controlador de pantalla SSD1306.
My code
- 0_91_OLED_Display_am_Raspberry_Pi_4e813f75-224f-4531-8d22-ecf7427adc67.zip - drivers i exemples python
Python library to use SSD1306-based 128x64 or 128x32 pixel OLED displays
- fryntiz -
librería (es) para pantallas OLED de 128x64 píxeles con el controlador SSD 1306
funciones :
- animacion(texto, amplitude, offset, velocity) → Muestra el texto pasado como animación
- imagen(ruta) → Recibe la ruta hacia la imagen que será mostrada
- informacion() → Muestra información sobre el estado de la raspberry
- 20200703 :
- 1x font USB
- 2x TC74A2 - i2a @ = 0x94 -> detalls
- 3x MCP 9800 - specs
data sheet
- 3x BC547 - NPN transistor, Vce (<45V), Ic (<100mA), W (&lr;625 mW), f (< 300 MHz), hfe (>110)
SAG & R4
Specs : url
- Broadcom BCM2711, Quad core Cortex-A72 (ARM v8) 64-bit SoC @ 1.5GHz - compte : Raspbian es de 32 bits
- 2 GB, 4 GB or 8 GB LPDDR4-3200 SDRAM
- 2x USB 3.0 ports; 2x USB 2.0 ports
- 1x Gigabit Ethernet
- 2.4 GHz and 5.0 GHz IEEE 802.11ac wireless
- Bluetooth 5.0, BLE
- 2 × micro-HDMI ports
Us 202102 : Home Assistant
NOOBS, 2020
Lets make it run :
- download NOOBS NOOBS_v3_5_1.zip onto MARS & Ubuntu
- expand into a directory, lets say "noobs_35"
- get rpi-imager
- download Raspberry Pi Imager for Ubuntu : imager_1.5_amd64.deb
- on Ubuntu, double click on the "*.deb" file to install rpi-imager
- format SD as FAT32, using rpi-imager
- copy the extracted files onto the SD card that you just formatted so that this file (INSTRUCTIONS-README.txt)
is at the root directory of the SD card.
Ara que engega i tenim terminal, fem :
- sudo apt update
- sudo apt full-upgrade ; url
- tenim "Raspbian 10, buster"
Raspbian, 2021
Tenim una micro SDHC "SanDisk Ultra" de 32 GB, clase 10, categoria A1
- ens baixem un buster
nicolau@mars:~/sebas/rspi/op_sys$ ls -al
2932156 -rw-rw-r-- 1 nicolau nicolau 3.002.523.031 Mar 13 20:49 2021-01-11-raspios-buster-armhf-full.zip
8400900 -rw-r--r-- 1 nicolau nicolau 8.602.517.504 Jan 11 14:32 2021-01-11-raspios-buster-armhf-full.img
- conectem la SD al MARS :
nicolau@mars:~/sebas/rspi/op_sys$ lsblk -p | grep /dev/sd
nicolau@mars:~$ lsblk -p | grep /dev/sd
/dev/sda 8:0 0 232.9G 0 disk
└─/dev/sda1 8:1 0 232.9G 0 part /
/dev/sdb 8:16 1 14.9G 0 disk
├─/dev/sdb1 8:17 1 256M 0 part /media/nicolau/boot
└─/dev/sdb2 8:18 1 14.6G 0 part /media/nicolau/rootfs
- esborrem tot el contingut :
nicolau@mars:~/sebas/rspi/op_sys$ sudo fdisk /dev/sdb
Command (m for help): p
Disk /dev/sdb: 29.7 GiB, 31914983424 bytes, 62333952 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00000000
Device Boot Start End Sectors Size Id Type
/dev/sdb1 2048 62333951 62331904 29.7G 83 Linux
- crear filesystem :
nicolau@mars:~/sebas/rspi/op_sys$ sudo umount /dev/sdb1
nicolau@mars:~/sebas/rspi/op_sys$ sudo mkfs.vfat -F 32 /dev/sdb1
mkfs.fat 4.1 (2017-01-24)
- posem el Raspbian :
nicolau@mars:~/sebas/rspi/op_sys$ sudo dd bs=4M if=./2021-01-11-raspios-buster-armhf-full.img of=/dev/sdb conv=fsync status=progress
8594128896 bytes (8.6 GB, 8.0 GiB) copied, 414 s, 20.8 MB/s
2051+0 records in
2051+0 records out
8602517504 bytes (8.6 GB, 8.0 GiB) copied, 514.173 s, 16.7 MB/s
- apareix el GUI, obrim la wifi i permitim conexions remotes
$ sudo systemctl enable ssh
$ sudo systemctl start ssh
$ sudo apt update
pi@raspberrypi:~ $ sudo apt-get install moreutils
Reading package lists... Done
pi@raspberrypi:~ $ sudo apt-get full-upgrade
- create own user :
$ sudo adduser sebas
Adding user `sebas' ...
Adding new group `sebas' (1001) ...
Adding new user `sebas' (1001) with group `sebas' ...
Creating home directory `/home/sebas' ...
- make it super-user :
pi@raspberrypi:/home $ sudo adduser sebas sudo
Adding user `sebas' to group `sudo' ...
Adding user sebas to group sudo
Done.
- create some dirs and log files :
sebas@r4:~ $ mkdir /home/sebas/eines
sebas@r4:~ $ mkdir /home/sebas/eines/backup
sebas@r4:~ $ mkdir /home/sebas/logs
sebas@r4:~ $ mkdir /home/sebas/logs/oldies
sebas@r4:~ $ mkdir /home/sebas/python
sebas@r4:~ $ touch /home/sebas/logs/r4_start.log
sebas@r4:~ $ touch /home/sebas/logs/engegades.log
sebas@r4:~ $ touch /home/sebas/logs/last_boot_time.log
sebas@r4:~ $ touch /home/sebas/logs/send_telegram.log
sebas@r4:~ $ touch /home/sebas/logs/msg_a_tg.log
sebas@r4:~ $ touch /home/sebas/logs/fer_backup.log
sebas@r4:~ $ touch /home/sebas/logs/enviar_html_a_tinet.log
sebas@r4:~ $ touch /home/sebas/logs/1_netejar.log
sebas@r4:~ $ touch /home/sebas/logs/wifi_wd.log
- copy some files :
/home/sebas/.bash_aliases
/home/sebas/eines/r4_start.sh
/home/sebas/.config/systemd/user/r4_start.service
/home/sebas/eines/backup/fer_backup.sh
/home/sebas/eines/backup/llista_fitxers.txt
/home/sebas/logs/1_netejar.sh
/home/sebas/python/telegram/client.py
/home/sebas/python/telegram/msg_a_tg.sh
/home/sebas/python/telegram/retry_msg_a_tg.sh
- start "initial" service
sebas@raspberrypi:~ $ systemctl --user enable r4_start.service
sebas@raspberrypi:~ $ systemctl --user start r4_start.service
sebas@raspberrypi:~ $ systemctl --user status r4_start.service
● r4_start.service - Raspberry 4 startup code - /home/sebas/.config/systemd/user/r4_start.service - (v1.l)
Loaded: loaded (/home/sebas/.config/systemd/user/r4_start.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Sun 2021-03-14 00:26:39 CET; 2s ago
Process: 1105 ExecStart=/home/sebas/eines/r4_start.sh (code=exited, status=0/SUCCESS)
Main PID: 1105 (code=exited, status=0/SUCCESS)
- start user crontab
sebas@r4:~/eines $ crontab -u sebas cron_sebas.txt
Les feines programades que hi tenim ar R4 son :
sebas@r4:~/eines $ cat cron_sebas.txt
##########################################################
# minute (0-59), #
# | hora (0-23), #
# | | dia del mes (1-31), #
# | | | mes (1-12), #
# | | | | dia de la semana (1-7 donde 1=Lunes) #
# | | | | | comandos #
##########################################################
29 1 2 * * /home/pi/eines/1_netejar.sh
15 1 * * * cd /home/pi/eines/backup && /home/pi/eines/backup/fer_backup.sh
0,30 * * * * cd /home/pi/python/tinet && /home/pi/python/tinet/enviar_html_a_tinet.py &>> /home/pi/logs/enviar_html_a_tinet.log
6 2 * * * /home/pi/python/telegram/msg_a_tg.sh kron
- per mirar els errors del cron ens cal "mail" :
$ sudo apt-get install mailutils
El primer missatge es
sebas@r4:~ $ mail
Cannot open mailbox /var/mail/sebas: Permission denied
No mail for sebas
Send a first message to the user :
sebas@r4:~ $ mail -s "Test Subject" sebas@localhost < /dev/null
mail: Null message body; hope that's ok
And here it is the mailbox :
sebas@r4:~ $ ls -l /var/mail
total 12
4 -rw-rw---- 1 sebas mail 461 Mar 14 19:22 sebas
sebas@r4:~ $ mail
"/var/mail/sebas": 1 message 1 new
>N 1 sebas@r4 Sun Mar 14 19:22 14/421 Test Subject
? q
Held 1 message in /var/mail/sebas
R4 start service
The service definition is :
sebas@raspberrypi:~/.config/systemd/user $ cat r4_start.service
[Unit]
Description=Raspberry 4 startup code - /home/sebas/.config/systemd/user/r4_start.service - (v1.l)
; v 1.l - R4
; v 1.k - detalls versions
; v 1.j - oneshot
; v 1.i - location
; v 1.h - user sebas
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
; simple - a long-running process that does not background itself and stays attached to the shell
; forking - a typical daemon that forks itself detaching it from the process that ran it, effectively backgrounding itself
; oneshot - a short-lived process that is expected to exit
Restart=no
WorkingDirectory=/home/sebas/eines
ExecStart=/home/sebas/eines/r4_start.sh
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=r4_start
Environment=NODE_ENV=production
[Install]
WantedBy=default.target
The service job is :
sebas@raspberrypi:~/eines $ cat r4_start.sh
#!/bin/bash
# "oneshot" service run at R4 start
# Raspberry Pi Zero Cookbook
# Starup Log Script
# Logs basic RPZ Info on system startup
# after modifying it, run :
# sudo service rpz_start status
# sudo systemctl daemon-reload
# Versions
# 20200731 v 2.c - una sola versio, millors missatges al log
# 20200801 v 2.d - engegar LED duty cycle
# 20200806 v 2.e - no fer servir >>> /dev/null
# 20200806 v 2.f - "oneshot" - TG in foreground, DUTY (leds) to another service
# 20200809 v 2.g - remove extra timestamp
# 20200818 v 2.h - save simple boot time file to send to Tinet
# 20200823 v 2.i - trace only starting timestamp, as old times
# 20210317 v 2.j - pass ID to TG
# 20220404 v 2.k - user pi - set paths relative
# 20220405 v 2.l - log numbering
szWho=$1
myVersio="v 2.l"
myBase="/home/pi"
myBaseLog=$myBase"/logs"
myLog=$myBaseLog"/1_r4_start.log"
tinetFN=$myBaseLog"/last_boot_time.log"
engegaFN=$myBaseLog"/engegades.log"
date_name=`date +"Y%y/M%m/D%d"`
time_name=`date +"h%H:m%M:s%S"`
szTs="$date_name - $time_name"
szId="+++ +++ +++ ($szTs) [$HOSTNAME] ($0) - versio $myVersio +++ +++ +++"
# timestamp system start at own log file
echo -e "\n$szId" >> $myLog
echo "$szId" >> $engegaFN
# simple timestamp into file - used to send HTML to Tinet
echo $szTs > $tinetFN
# trace in /var/log/syslog
logger -i -p user.info $szId
# send msg to TG
/home/pi/python/telegram/msg_a_tg.sh $szWho &>> $myLog
rc=$?
echo ">>> TG rc $rc" >> $myLog
# write some funny info
TEMP=`/opt/vc/bin/vcgencmd measure_temp | cut -d "=" -f 2`
GPU=`/opt/vc/bin/vcgencmd get_mem gpu | cut -d "=" -f 2`
ARM=`/opt/vc/bin/vcgencmd get_mem arm | cut -d "=" -f 2`
STATUS=`/opt/vc/bin/vcgencmd pm_get_status`
echo Current core temperature {$TEMP} >> $myLog
echo GPU RAM {$GPU} - CPU RAM {$ARM} >> $myLog
echo RPZ Status {$STATUS} >> $myLog
szId="--- --- --- ($szTs) [$HOSTNAME] ($0) - versio $myVersio --- --- ---"
echo $szId >> $myLog
exit 0
R4 sends to TG
R4 sends a message to TG bot in 2 situations :
- power-on, from r4_start.service
- at 02:06 every morning, from cron_sebas.txt
R4 backup using email
Install Mutt :
sebas@r4:~ $ sudo apt-get install mutt
sebas@r4:~ $ mkdir -p ~/.mutt/cache/headers
sebas@r4:~ $ mkdir ~/.mutt/cache/bodies
sebas@r4:~ $ touch ~/.mutt/certificates
Configure Mutt : url
Test Mutt is working - see ~/.muttdebug0 file
sebas@r4:~ $ echo "my BODY" | mutt -d 5 -s "my SUBJECT" -- mydestinationemail@gmail.com
Setup daily backup
sebas@r4:/etc/cron.daily $ sudo ln -s /home/sebas/eines/backup/fer_backup.sh envia_tgz_per_email
Compte que s'executa sota usuari "root" i no sap on posar el fitxer "tgz" -
see cron with explicit paths
R4 sends to Tinet
Every 1/2 hour R4 sends a HTML page to Tinet -
see R4 crontab
2022, el R4 és mort - el reinstalo
At boot, I see :
board: c03112 b8e2879d dc:a6:32:7f:45:7c
boot: mode SD 1 order f41 retry 0/0 restart 0/-1
SD: casrd detected 0003534
part: 0 mbr []
updates: enabled 1
fw: start4.elf fixup4.dat
net: down ip: 0.0.0.0 sn: 0.0.0.0 gw: 0.0.0.0
tftp: 0.0.0.0 00:00:00:00:00:00
Reset USB port-power 1000 ms
lba: 8192 oem: 'mkfs.fat' volume: ' boot '
rsc 32 fat-sectors 4033 c-count 516190 c-size 1 r-dir 2
Partition: 0
lba: 8192 oem: 'mkfs.fat' volume: ' boot '
rsc 32 fat-sectors 4033 c-count 516190 c-size 1 r-dir 2
Read config.txt bytes 1784 hnd 0x000003e5 hash '6c0f63...'
recover4.eld not found (6)
recovery.elf not found (6)
Read start4.elf bytes 2228800 hnd 0x00013669 hash 'dce1545...'
Read fixup4.dat bytes 5448 hnd 0x000180c3 hash '4109cea...'
0x00c03112 0x00000000 0x000000ff
MEM GPU: 76 ARM: 948 TOTAL: 1024
Sugerencia :
cat 2021-05-07-raspios-buster-armhf.img > dev/sdb && sync && eject /dev/sdb
/boot/config.txt complert
Fitxer mestre en botar :
/boot/config.txt"
What is config.txt?
# For more options and information see http://rptl.io/configtxt
The Raspberry Pi uses a configuration file instead of the BIOS you would expect to find on a conventional PC.
The system configuration parameters, which would traditionally be edited and stored using a BIOS,
are stored instead in an optional text file named config.txt.
This is read by the GPU before the ARM CPU and Linux are initialised.
It must therefore be located on the first (boot) partition of your SD card, alongside bootcode.bin and start.elf
docu
Compte - 202410 (nou R3) diu : The file you are looking for has moved to /boot/firmware/config.txt
Atencio : trobo legacy options not used by Bookworm (as disable_overscan)
The config.txt options described here are considered legacy settings, are not used by Raspberry Pi OS Bookworm, and are no longer officially supported.
# For more options and information see
#
http://rpf.io/configtxt
# Some settings may impact device functionality. See link above for details
# uncomment if you get no picture on HDMI for a default "safe" mode
#hdmi_safe=1
# uncomment this if your display has a black border of unused pixels visible
# and your display can output without overscan
#disable_overscan=1
# uncomment the following to adjust overscan. Use positive numbers if console
# goes off screen, and negative if there is too much border
#overscan_left=16
#overscan_right=16
#overscan_top=16
#overscan_bottom=16
# uncomment to force a console size. By default it will be display's size minus
# overscan.
#framebuffer_width=1280
#framebuffer_height=720
# uncomment if hdmi display is not detected and composite is being output
#hdmi_force_hotplug=1
# uncomment to force a specific HDMI mode (this will force VGA)
#hdmi_group=1
#hdmi_mode=1
# uncomment to force a HDMI mode rather than DVI. This can make audio work in
# DMT (computer monitor) modes
#hdmi_drive=2
# uncomment to increase signal to HDMI, if you have interference, blanking, or
# no display
#config_hdmi_boost=4
# uncomment for composite PAL
#sdtv_mode=2
#uncomment to overclock the arm. 700 MHz is the default.
#arm_freq=800
# Uncomment some or all of these to enable the optional hardware interfaces
#dtparam=i2c_arm=on
#dtparam=i2s=on
#dtparam=spi=on
# Uncomment this to enable infrared communication.
#dtoverlay=gpio-ir,gpio_pin=17
#dtoverlay=gpio-ir-tx,gpio_pin=18
# Additional overlays and parameters are documented /boot/overlays/README
# Enable audio (loads snd_bcm2835)
dtparam=audio=on
[pi4]
# Enable DRM VC4 V3D driver on top of the dispmanx display stack
dtoverlay=vc4-fkms-v3d
max_framebuffers=2
[all]
#dtoverlay=vc4-fkms-v3d
# send logs to UART so MARS can see it
enable_uart=1
Use "$ vcgencmd dispmanx_list"
Anem a veure'n els detalls :
# Uncomment some or all of these to enable the optional hardware interfaces
dtparam=i2c_arm=on ; enable I2C on the GPIO pins
#dtparam=i2s=on ; enable I2S audio hardware
dtparam=spi=on ; enable SPI driver
Fem SD nova per R4
- get 2022-01-28-raspios-bullseye-arm64.zip here
- expand it to 2022-01-28-raspios-bullseye-armhf.img
- {MARS} sudo apt install rpi-imager
nicolau@mars:~$ sudo apt install rpi-imager
[sudo] password for nicolau:
Reading package lists... Done
Building dependency tree
Reading state information... Done
rpi-imager is already the newest version (1.5).
0 upgraded, 0 newly installed, 0 to remove and 65 not upgraded.
- {MARS} Pi imager v1.5 ... writing
- esborrem la SD :
nicolau@mars:~/sebas/rspi/op_sys$ sudo mkfs.vfat -F 32 /dev/sdb1
nicolau@mars:~/sebas/rspi/op_sys$ sudo dd bs=4M if=./2022-01-28-raspios-bullseye-armhf.img of=/dev/sdb conv=fsync status=progress
4227858432 bytes (4.2 GB, 3.9 GiB) copied, 178 s, 23.7 MB/s
1010+0 records in
1010+0 records out
4236247040 bytes (4.2 GB, 3.9 GiB) copied, 294.961 s, 14.4 MB/s
nicolau@mars:~/sebas/rspi/op_sys$ df -h | grep sd --- compte que no hi hagi res de Guinous
/dev/sda1 229G 125G 92G 58% /
/dev/sdb1 253M 49M 204M 20% /media/nicolau/boot
/dev/sdb2 3.6G 3.0G 395M 89% /media/nicolau/rootfs
nicolau@mars:~$ lsblk -p | grep /dev/sd {32 GB}
/dev/sda 8:0 0 232.9G 0 disk
└─/dev/sda1 8:1 0 232.9G 0 part /
/dev/sdb 8:16 1 29.7G 0 disk
├─/dev/sdb1 8:17 1 256M 0 part /media/nicolau/boot
└─/dev/sdb2 8:18 1 29.5G 0 part /media/nicolau/rootfs
Si volem modificar algun fitxer a ma :
/boot/config.txt
/boot/cmdline.txt
/rootfs/etc/fstab
- botem la nova SD :
---[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(172,2) ]---
- esborrem la SD fent servir rpi-imager de Ubuntu
[INSTRUCTIONS-README.txt] using gparted (or the command line version parted), format the entire disk as FAT32
- get latest NOOBS {best docu} :
NOOBS_v3_8_0.zip
Download and extract the files from the NOOBS zip file :
/home/nicolau/sebas/rspi/op_sys/2022/sd -> /
Copy the extracted files onto the SD card that you just formatted so that these files are at the root directory of the SD card.
Please note that in some cases it may extract the files into a folder;
if this is the case, then please copy across the files from inside the folder rather than the folder itself.
- **Raspberry Pi 4 Model B:** display must be connected to HDMI port closest to power jack.
- boot problems :
edit /boot/config.txt to include
hdmi_force_hotplug=1
14 solutions,
6 more
- tornem a provar - 20220328 :
- conectem la SD al MARS i la esborrem amb rpi-imager de Ubuntu
- tenim la imatge :
- al MARS engeguem "/home/Downloads/balenaEtcher-1.5.113-x64.AppImage", seleccionem ".img" i la SD
- obtenim :
nicolau@mars:~$ dfh
/dev/sda1 229G 138G 80G 64% /
/dev/sdb1 253M 30M 223M 12% /media/nicolau/boot
/dev/sdb2 3.5G 2.9G 443M 87% /media/nicolau/rootfs
nicolau@mars:~$ lsblk -p | grep /dev/sd
/dev/sda 8:0 0 232.9G 0 disk
└─/dev/sda1 8:1 0 232.9G 0 part /
/dev/sdb 8:16 1 29.7G 0 disk
├─/dev/sdb1 8:17 1 256M 0 part /media/nicolau/boot
└─/dev/sdb2 8:18 1 3.6G 0 part /media/nicolau/rootfs
- bota ? "Resized root filesystem" -> blank screen
- baixem Raspbian "lite" : 2022-01-28-raspios-bullseye-arm64-lite.zip
nicolau@mars:~$ dfh
/dev/sda1 229G 147G 71G 68% /
/dev/sdb1 253M 30M 223M 12% /media/nicolau/boot
/dev/sdb2 1.6G 1.2G 338M 78% /media/nicolau/rootfs
nicolau@mars:~/sebas/_local_tinet_files$ lsblk -p | grep /dev/sd
/dev/sda 8:0 0 232.9G 0 disk
└─/dev/sda1 8:1 0 232.9G 0 part /
/dev/sdb 8:16 1 29.7G 0 disk
├─/dev/sdb1 8:17 1 256M 0 part /media/nicolau/boot
└─/dev/sdb2 8:18 1 1.6G 0 part /media/nicolau/rootfs
- compro cable USB-2-TTL : intento log 2 serial port
No veig els missatges de R4, fins que poso enable_uart=1 a /boot/config.txt
Ara veig els missatges de engegada, fins q aqui es penja :
[ 5.493569] systemd[1]: modprobe@configfs.service: Succeeded.
[ 5.504223] systemd[1]: Finished Load Kernel Module configfs.
[ 5.518822] systemd[1]: modprobe@drm.service: Succeeded.
[ 5.528700] systemd[1]: Finished Load Kernel Module drm.
[ 5.543254] systemd[1]: modprobe@fuse.service: Succeeded.
[ 5.553400] systemd[1]: Finished Load Kernel Module fuse.
[ 5.567745] systemd[1]: Finished File System Check on Root Device.
[ 5.582857] systemd[1]: Finished Load Kernel Modules.
[ 5.597842] systemd[1]: Finished Set the console keyboard layout.
[ 5.611712] systemd[1]: Started Journal Service.
Debian GNU/Linux 11 raspberrypi ttyS0
raspberrypi login:
CTRL-A Z for help | 115200 8N1 | NOR | Minicom 2.7.1 | VT102 | Offline | ttyUSB0
- Lets try an "old" NOOBS :
You can find older versions at http://downloads.raspberrypi.org/ and particularly at
http://downloads.raspberrypi.org/NOOBS/images/
20220402 -
- get 3.3.0 : 07.2020 -> nicolau@mars:~/sebas/rspi/op_sys/2022_3.5/noobs_3.5
- format SD using rpi-imager
- copy from MARS to SD pointing "INSTRUCTIONS-README.txt" at the root directory of SD card
- modificar "/boot/config.txt" per contenir "enable_uart=1"
- al MARS, engegar "minicom -b 115200 -D /dev/ttyUSB0"
- power-on the R4 : mostra 2 SO's i demana quin instalar -> Raspbian
- success !
Configurem
- set wifi static ip 192.168.1.200
- enable ssh : "sudo systemctl enable ssh" + "sudo systemctl start ssh"
- set ssh welcome message
- set timezone, using "sudo raspi-config" - url
- set hostname, using "sudo raspi-config"
- Updating and Upgrading Raspberry Pi OS - Using APT
The easiest way to manage installing, upgrading, and removing software is using APT (Advanced Packaging Tool) from Debian.
To update software in Raspberry Pi OS, you can use the apt tool from a Terminal window.
APT keeps a list of software sources on your Raspberry Pi in a file at /etc/apt/sources.list.
Before installing software, you should update your package list with apt update.
Go ahead and open a Terminal window and type: sudo apt update
pi@raspberrypi:~ $ sudo apt update
Get:1 http://archive.raspberrypi.org/debian buster InRelease [32.6 kB]
Get:2 http://raspbian.raspberrypi.org/raspbian buster InRelease [15.0 kB]
E: Repository 'http://raspbian.raspberrypi.org/raspbian buster InRelease' changed its 'Suite' value from 'stable' to 'oldstable'
N: This must be accepted explicitly before updates for this repository can be applied. See apt-secure(8) manpage for details.
Do you want to accept these changes and continue updating from this repository? [y/N]
Reading package lists... Done
Building dependency tree
Reading state information... Done
455 packages can be upgraded. Run 'apt list --upgradable' to see them.
$ apt list --upgradable
$ pi@raspberrypi:~ $ sudo apt-get dist-upgrade ; 45 minuts
$ sudo apt autoremove
$ sudo apt full-upgrade ; res a fer
Next, upgrade all your installed packages to their latest versions with the following command: sudo apt full-upgrade
Note that full-upgrade is used in preference to a simple upgrade, as it also picks up any dependency changes that may have been made.
Now, enter "sudo raspi-config" and (8) "update" the tool, then
(2) "6 Advanced options" + "A7 Bootloader Version" + "E1 Latest"
Verify bootloader is up to date using the command "rpi-eeprom-update"
pi@raspberrypi:~ $ sudo rpi-eeprom-update
BOOTLOADER: up to date
CURRENT: Thu 10 Mar 2022 11:57:12 AM UTC (1646913432)
LATEST: Thu 10 Mar 2022 11:57:12 AM UTC (1646913432)
RELEASE: stable (/lib/firmware/raspberrypi/bootloader/stable)
Use raspi-config to change the release.
VL805_FW: Dedicated VL805 EEPROM
VL805: up to date
CURRENT: 000138a1
LATEST: 000138a1
Or ...
sudo apt update
sudo apt full-upgrade
sudo rpi-eeprom-update -a
sudo reboot
Engeguem scripts :
Comanda per copiar des R4 un fitxer de MARS :
pi@raspberrypi:~ $ scp nicolau@192.168.1.54:/home/nicolau/sebas/rspi/backups/r4/20220403/home/sebas/.config/systemd/user/* .
Software R4-2022
nmap
pi@R4:~ $ nmap -sP 192.168.1.0-255
-bash: nmap: command not found
pi@R4:~ $ sudo apt update
Get:1 http://packages.azlux.fr/debian bullseye InRelease [3,988 B]
Get:2 http://packages.azlux.fr/debian bullseye/main armhf Packages [3,552 B]
Get:3 http://raspbian.raspberrypi.org/raspbian buster InRelease [15.0 kB]
Get:4 http://archive.raspberrypi.org/debian buster InRelease [32.6 kB]
Get:5 http://archive.raspberrypi.org/debian buster/main armhf Packages [391 kB]
Get:6 http://raspbian.raspberrypi.org/raspbian buster/main armhf Packages [13.0 MB]
Fetched 13.5 MB in 2min 46s (81.1 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
86 packages can be upgraded. Run 'apt list --upgradable' to see them.
pi@R4:~ $ apt list --upgradable
Listing... Done {llista ben llarga}
pi@R4:~ $ sudo apt-get dist-upgrade {triga una bona estona}
pi@R4:~ $ sudo apt install -y nmap
pi@R4:~ $ nmap --version
Nmap version 7.70 ( https://nmap.org )
Platform: arm-unknown-linux-gnueabihf
Compiled with: liblua-5.3.3 openssl-1.1.1d libssh2-1.8.0 libz-1.2.11 libpcre-8.39 libpcap-1.8.1 nmap-libdnet-1.12 ipv6
Compiled without:
Available nsock engines: epoll poll select
lindevs
Displays MAC when used under "sudo" !!!
log2ram
Compte : no es pot executar cap shell, com "esborrar.sh" dins de "/home/user/logs", si el directori el controla log2ram.
pi@raspberrypi:~ $ echo "deb [signed-by=/usr/share/keyrings/azlux-archive-keyring.gpg] \
http://packages.azlux.fr/debian/ bullseye main" | sudo tee /etc/apt/sources.list.d/azlux.list
deb [signed-by=/usr/share/keyrings/azlux-archive-keyring.gpg] http://packages.azlux.fr/debian/ bullseye main
pi@raspberrypi:~ $ sudo wget -O /usr/share/keyrings/azlux-archive-keyring.gpg https://azlux.fr/repo.gpg
--2022-04-02 22:07:45-- https://azlux.fr/repo.gpg
Resolving azlux.fr (azlux.fr)... 37.58.241.234
Connecting to azlux.fr (azlux.fr)|37.58.241.234|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2255 (2.2K) [application/octet-stream]
Saving to: ‘/usr/share/keyrings/azlux-archive-keyring.gpg’
/usr/share/keyrings/azlux-archive 100%[====================================================>] 2.20K --.-KB/s in 0s
2022-04-02 22:07:46 (10.7 MB/s) - ‘/usr/share/keyrings/azlux-archive-keyring.gpg’ saved [2255/2255]
pi@raspberrypi:~ $ sudo apt update
Hit:1 http://raspbian.raspberrypi.org/raspbian buster InRelease
Get:2 http://packages.azlux.fr/debian bullseye InRelease [3,988 B]
Hit:3 http://archive.raspberrypi.org/debian buster InRelease
Get:4 http://packages.azlux.fr/debian bullseye/main armhf Packages [3,426 B]
Fetched 7,414 B in 1s (7,001 B/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
All packages are up to date.
pi@raspberrypi:~ $ sudo apt install log2ram
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
log2ram
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 4,204 B of archives.
After this operation, 0 B of additional disk space will be used.
Get:1 http://packages.azlux.fr/debian bullseye/main armhf log2ram all 1.6.1 [4,204 B]
Fetched 4,204 B in 0s (31.5 kB/s)
Selecting previously unselected package log2ram.
(Reading database ... 167466 files and directories currently installed.)
Preparing to unpack .../archives/log2ram_1.6.1_all.deb ...
Unpacking log2ram (1.6.1) ...
Setting up log2ram (1.6.1) ...
Created symlink /etc/systemd/system/sysinit.target.wants/log2ram.service → /etc/systemd/system/log2ram.service.
Created symlink /etc/systemd/system/timers.target.wants/log2ram-daily.timer → /etc/systemd/system/log2ram-daily.timer.
##### Reboot to activate log2ram #####
##### edit /etc/log2ram.conf to configure options ####
Configure :
$ cat /etc/log2ram.conf
# Size for the ram folder, it defines the size the log folder will reserve into the RAM.
SIZE=40M
# Variable for folders to put in RAM.
# example : PATH_DISK="/var/log;/home/test/FolderInRam"
PATH_DISK="/var/log;/home/sebas/logs"
Is it working?
pi@raspberrypi:~ $ systemctl status log2ram
● log2ram.service - Log2Ram
Loaded: loaded (/etc/systemd/system/log2ram.service; enabled; vendor preset: enabled)
Active: active (exited) since Sat 2022-04-02 22:14:19 BST; 1min 57s ago
Process: 326 ExecStart=/usr/local/bin/log2ram start (code=exited, status=0/SUCCESS)
Main PID: 326 (code=exited, status=0/SUCCESS)
Apr 02 22:14:20 raspberrypi log2ram[326]: lightdm/x-0.log.old
Apr 02 22:14:20 raspberrypi log2ram[326]: private/
Apr 02 22:14:20 raspberrypi log2ram[326]: deleting log2ram.log
Apr 02 22:14:20 raspberrypi log2ram[326]: sent 1,896,470 bytes received 533 bytes 3,794,006.00 bytes/sec
Apr 02 22:14:20 raspberrypi log2ram[326]: total size is 1,893,956 speedup is 1.00
Apr 02 22:14:20 raspberrypi log2ram[326]: building file list ... done
Apr 02 22:14:20 raspberrypi log2ram[326]: ./
Apr 02 22:14:20 raspberrypi log2ram[326]: deleting log2ram.log
Apr 02 22:14:20 raspberrypi log2ram[326]: sent 57 bytes received 18 bytes 150.00 bytes/sec
Apr 02 22:14:20 raspberrypi log2ram[326]: total size is 0 speedup is 0.00
dos2unix
"sudo apt-get install dos2unix"
/tmp to RAM
Albert :
#
# pipaOS mount points
#
proc /proc proc defaults 0 0
/dev/mmcblk0p2 / ext4 defaults,noatime 0 0
/dev/mmcblk0p1 /boot vfat defaults,noatime 0 0
none /tmp tmpfs size=16m,mode=777 0 0
wikipedia tmpfs
speedtest
pi@R4:~/.local/bin $ sudo wget https://raw.githubusercontent.com/sivel/speedtest-cli/v2.1.3/speedtest.py
--2023-12-26 12:52:28-- https://raw.githubusercontent.com/sivel/speedtest-cli/v2.1.3/speedtest.py
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.111.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 65123 (64K) [text/plain]
Saving to: ‘speedtest.py’
speedtest.py 100%[==========================================================>] 63.60K --.-KB/s in 0.04s
2023-12-26 12:52:28 (1.70 MB/s) - ‘speedtest.py’ saved [65123/65123]
I obtenim :
pi@R4:~ $ speedtest.py
Retrieving speedtest.net configuration...
Testing from Yoigo (93.176.179.205)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by Voiped Telecom (Barcelona) [0.13 km]: 35.403 ms
Testing download speed................................................................................
Download: 23.83 Mbit/s
Testing upload speed................................................................................................
Upload: 42.79 Mbit/s
i@R4:~ $ speedtest.py --no-upload --simple
Cannot retrieve speedtest configuration
ERROR: HTTP Error 403: Forbidden
pi@R4:~ $ speedtest.py --secure
Retrieving speedtest.net configuration...
Testing from Yoigo (93.176.179.205)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by Netprotect (Madrid) [503.99 km]: 30.203 ms
Testing download speed................................................................................
Download: 21.31 Mbit/s
Testing upload speed................................................................................................
Upload: 37.40 Mbit/s
pi@R4:~ $ speedtest.py --no-upload --simple
Ping: 40.993 ms
Download: 17.60 Mbit/s
Upload: 0.00 Mbit/s
pi@R4:~ $ speedtest.py --no-upload --simple | grep Download
Download: 21.90 Mbit/s
R4 (final) TCP/IP configuration
We want a fixed IP on wifi and also on eth0, so no DHCP is required.
R4 TCP/IP configuration file
pi@R4:~ $ cat /etc/dhcpcd.conf
interface eth0
static ip_address=192.168.1.14/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 8.8.4.4
interface wlan0
static ip_address=192.168.1.200/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 8.8.4.4
TCPIP cfg
R3,
R4,
PiZero.
Restart service :
pi@R4:~ $ sudo systemctl restart dhcpcd.service
R4 final TCP/IP configuration
Resultat :
pi@R4:~ $ ifconfig
eth0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 192.168.1.14 netmask 255.255.255.0 broadcast 192.168.1.255
ether dc:a6:32:7f:45:7c txqueuelen 1000 (Ethernet)
wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.1.200 netmask 255.255.255.0 broadcast 192.168.1.255
ether dc:a6:32:7f:45:80 txqueuelen 1000 (Ethernet)
El Raspbian no pot tenir 2 IP's, així que si activem eth0, deix de funcionar wlan0 !
R4 bot
We shall run it as a service :
pi@R4:~/.config/systemd/user $ cat r4_bot.service
[Unit]
Description=Raspberry 4 bot code - /home/pi/.config/systemd/user/r4_bot.service - (v 1.e)
; v 1.a - start
; v 1.b - run "simple" and not "forking" to get python messages into log file
; v 1.c - remove StdOut and StdErr - we use "logging" inside python
; v 1.d - use "pi" user instead of "sebas"
; v 1.e - set 60 seg as restart timer
; systemctl --user status r4_bot.service
Wants=network-online.target
After=network-online.target
[Service]
Type=simple
; simple - a long-running process that does not background its self and stays attached to the shell
; forking - a typical daemon that forks itself detaching it from the process that ran it, effectively backgrounding itself
; oneshot - a short-lived process that is expected to exit
WorkingDirectory=/home/pi/python/telegram/telepot/
ExecStart=/home/pi/python/telegram/telepot/3_alby_bot.py
EnvironmentFile=/home/pi/python/telegram/telepot/my_bot.conf
; StandardOutput=append:/home/pi/logs/r4_bot.log
; StandardError=inherit
Restart=always
RestartSec=60
SyslogIdentifier=r4_bot
Environment=NODE_ENV=production
[Install]
WantedBy=default.target
pi@R4:~/python/telegram/telepot $ cat 3_alby_bot.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# implement "sag_r4" bot
# Versions :
# 20210612 - 2.b - use logging
# 20210613 - 2.c - pprint received message and chat object
# 2.d - INFO log
# 20210614 - 2.e - more commands
# 20221129 - 2.f - reinstall "telepot" - no "sebas" user
# 20221219 - 2.g - set ID also in help message
# 20230311 - 2.h - read termometer
# 20230606 - 2.i - return version
# 20230606 - 2.j - "Auto" IP
# 20230719 - 3.a - send answer to origin, not to Sebas ; display version in /help command
# https://core.telegram.org/bots/api#getchat - returns "chat" object
# https://core.telegram.org/bots/api#chat -
# service defined in /home/pi/.config/systemd/user/r4_bot.service
# systemctl status --user r4_bot.service
# systemctl stop --user r4_bot.service
# systemctl start --user r4_bot.service
import datetime
from gpiozero import CPUTemperature # python3 -m pip install gpiozero
import logging #
import os
from pprint import pprint #
import time
import tinytuya # python3 -m pip install pytuya
import telepot # https://telepot.readthedocs.io/en/latest/
# ============================================
# start of code
my_envir_var="SAG_TG_R4_TKN" # see /etc/environment - compte si engeguem com servei
sebas_id = "304588090" # Sebastia Altemir
szText = " " # create var to be used in handle
szVersio = "v 3.a.1" # identify code version
fnLog = '/home/pi/logs/r4_bot.log'
# logging.basicConfig( filename=fnLog, level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S' )
logging.basicConfig( filename=fnLog, level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S' )
logging.info( '\n\n *** R4 bot starts {%s} ***' % szVersio )
DEVICE_ID = "bfe483b0ac18224f06dqww" # sag 20230308
# DEVICE_IP = "192.168.1.130" # temperature meter, 2023/04/24 (sag) ---> use "Auto"
DEVICE_KEY = "fb9d5ba086f97ed4" # sag
DEVICE_VERS = "3.3"
szText = ">>> TinyTuya (Tuya Interface) version [%s]." % tinytuya.__version__
logging.info( szText )
# ===
def Get_Timestamp():
now = datetime.datetime.now()
szTS = now.strftime("%Y-%m-%d %H:%M:%S")
return szTS
# ===
def Get_Thermometer():
szText = '>>> Get_thermometer(auto ip)'
logging.info( szText )
szTEMP = '22 ºC'
iTEMP = 0
szText = '>>> Testing device {} with key {} version {}'.format( DEVICE_ID, DEVICE_KEY, DEVICE_VERS )
logging.info( szText )
d = tinytuya.OutletDevice( DEVICE_ID, "Auto", DEVICE_KEY ) # connect to device and fetch state ... "Auto" finds IP
d.set_version(3.3)
try:
dps = d.detect_available_dps()
szText = "+++ DPS {}".format(dps)
logging.info( szText )
iTEMP = dps['1']
except KeyError:
iTEMP = 0
except:
szT = Get_Timestamp()
print( "--- (%s) Unexpected error (%s)." % (szT, sys.exc_info() ) )
szText = '+++ Thermometer says {}.'.format(iTEMP)
logging.info( szText )
return iTEMP/10
# ===
def my_handle(msg):
logging.info( '\n*** (1) handle ***' )
# pprint(msg)
chat_id = msg['chat']['id']
new_command = msg['text']
szText = "*** received command is {%s} ***" % new_command
logging.info( szText )
chat_id = telepot.glance(msg)
content_type, chat_type, chat_id = telepot.glance(msg)
# print( "CT(%s), CT(%s), ID(%s)" % ( content_type, chat_type, str(chat_id) ) )
szText = "CT(%s), CT(%s), ID(%s)" % ( content_type, chat_type, str(chat_id) )
logging.info( szText )
objChat = bot.getChat( chat_id ) # get all info of a user - returns a "Chat" object
# pprint(objChat)
# Printing dictionary
# print ("Original dictionary is : " + str(objChat))
# using in operator to get key and value
# print ("Dict key-value are : ")
# for i in objChat :
# print(i, objChat[i])
if content_type == 'text': # make sure
if new_command == '/temp':
cpu = CPUTemperature()
result = str( cpu.temperature )
mytemp = ">>> CPU at "+result+" ºC"
bot.sendMessage(chat_id, mytemp)
else:
if new_command == '/talk':
myId = objChat['id']
myUserName = objChat['last_name']
myFirstName = objChat['first_name']
myMsg = ">>> ["+myFirstName+"] ("+str(chat_id)+") - cuyons quin fred ºC"
bot.sendMessage( chat_id, myMsg )
else:
if new_command == '/term':
szText = ">>> user request TEMP"
logging.info( szText )
myUserName = objChat['last_name']
myFirstName = objChat['first_name']
# iT = 0
iT = Get_Thermometer()
szText = "+++ thermometer {} says {}".format(szVersio,iT)
logging.info( szText )
myMsg = ">>> ["+myFirstName+"] thermometer indicates " + str(iT) + 'ºC'
bot.sendMessage( chat_id, myMsg )
else:
if new_command == '/help':
myUserName = objChat['last_name']
myFirstName = objChat['first_name']
myMsg = ">>> ["+myFirstName+"] bot version("+szVersio+") use /temp or /talk or /term"
bot.sendMessage( chat_id, myMsg )
else:
szErr = 'what is ('+new_command+') ? use /help'
bot.sendMessage( chat_id, szErr )
try:
szTxt = '*** (1) get token {}.'.format(my_envir_var)
logging.info( szTxt )
my_token = os.environ[ my_envir_var ] # /etc/environment if not a service
lng = len( my_token )
szTxt = '*** (1) llegit token {}.'.format(my_token)
logging.info( szTxt )
szTxt = '*** (1) llargada token {}.'.format(lng)
logging.info( szTxt )
logging.info( '*** (2) - telepot.Bot' )
bot = telepot.Bot( my_token )
logging.info( '*** (2) - {%s}.' % ( bot.getMe() ) )
bot.message_loop(my_handle)
except KeyError:
logging.info( '--- (e) Environment variable (%s) does not exist' % my_envir_var )
while True:
time.sleep(10)
El log normal es aquest :
pi@R4:~/logs $ cat r4_bot.log
24/12/2024 18:08:14
*** (1) handle ***
24/12/2024 18:08:14 *** received command is {/temp} ***
24/12/2024 18:08:14 CT(text), CT(private), ID(304588090)
24/12/2024 18:08:20
*** (1) handle ***
24/12/2024 18:08:20 *** received command is {/talk} ***
24/12/2024 18:08:20 CT(text), CT(private), ID(304588090)
24/12/2024 18:08:28
*** (1) handle ***
24/12/2024 18:08:28 *** received command is {/term} ***
24/12/2024 18:08:28 CT(text), CT(private), ID(304588090)
24/12/2024 18:08:28 >>> user request TEMP
24/12/2024 18:08:28 >>> Get_thermometer(auto ip)
24/12/2024 18:08:28 >>> Testing device bfe483b0ac18224f06dqww with key fb9d5ba086f97ed4 version 3.3
24/12/2024 18:08:33 +++ DPS {'1': 159, '2': 65, '9': 'c', '10': 390, '11': 0, '12': 60, '13': 20, '14': 'cancel', '15': 'upperalarm', '21': True, '101': False, '102': 0, '103': 0, '104': 0, '105': 0, '106': 0, '107': 0}
24/12/2024 18:08:33 +++ Thermometer says 159.
24/12/2024 18:08:33 +++ thermometer v 3.a.1 says 15.9
To install the bot, we do :
pi@R4:~ $ python3 -m pip install telepot
...
pi@R4:~ $ python3 -m pip install --upgrade pip
Defaulting to user installation because normal site-packages is not writeable
Collecting pip
Downloading https://www.piwheels.org/simple/pip/pip-24.0-py3-none-any.whl (2.1 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 1.4 MB/s eta 0:00:00
Installing collected packages: pip
Successfully uninstalled pip-23.1.2
Successfully installed pip-24.0
The environment file is :
pi@R4:~/python/telegram/telepot $ cat my_bot.conf
SAG_TG_R4_TKN="1801244684:AaEFF2BOK27xkxjNKokvqClEXzWOLj3TIYs"
I el estat normal/funcionant del servei es :
pi@R4:~/python/telegram/telepot $ systemctl --user status r4_bot.service
● r4_bot.service - Raspberry 4 bot code - /home/pi/.config/systemd/user/r4_bot.service - (v 1.d)
Loaded: loaded (/home/pi/.config/systemd/user/r4_bot.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2022-11-29 20:00:18 CET; 53s ago
Main PID: 25100 (python3)
CGroup: /user.slice/user-1000.slice/user@1000.service/r4_bot.service
└─25100 python3 /home/pi/python/telegram/telepot/3_alby_bot.py
Nov 29 20:00:18 R4 systemd[877]: Started Raspberry 4 bot code - /home/pi/.config/systemd/user/r4_bot.service - (v 1.d).
R4 GUI restart
When I re-plug the Raspberry HDMI to TV set, no GUI comes up -
forum
pi@R4:~ $ geany &
[1] 21116
pi@R4:~ $ Unable to init server: Could not connect: Connection refused
Geany: cannot open display
^C
[1]+ Exit 1 geany
Lets try X11 :
pi@R4:~ $ X -configure
X.Org X Server 1.20.4
X Protocol Version 11, Revision 0
Build Operating System: Linux 5.4.0-109-generic armv8l Raspbian
Current Operating System: Linux R4 5.10.103-v7l+ #1529 SMP Tue Mar 8 12:24:00 GMT 2022 armv7l
Kernel command line: coherent_pool=1M 8250.nr_uarts=1 snd_bcm2835.enable_compat_alsa=0 snd_bcm2835.enable_hdmi=1 smsc95xx.macaddr=DC:A6:32:7F:45:7C vc_mem.mem_base=0x3ec00000 vc_mem.mem_size=0x40000000 console=ttyS0,115200 console=tty1 root=/dev/mmcblk0p7 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait splash
Build Date: 04 August 2022 12:56:42PM
xorg-server 2:1.20.4-1+rpt4+deb10u5 (https://www.debian.org/support)
Current version of pixman: 0.36.0
Before reporting problems, check http://wiki.x.org
to make sure that you have the latest version.
Markers: (--) probed, (**) from config file, (==) default setting,
(++) from command line, (!!) notice, (II) informational,
(WW) warning, (EE) error, (NI) not implemented, (??) unknown.
(==) Log file: "/home/pi/.local/share/xorg/Xorg.0.log", Time: Sat Dec 31 18:51:41 2022
List of video drivers:
fbturbo
modesetting
fbdev
No devices to configure. Configuration failed.
(EE) Server terminated with error (2). Closing log file.
Try xrandr :
pi@R4:~ $ xrandr
Can't open display :0.0
pi@r3-64gb:~ $ DISPLAY=:0 xrandr
Screen 0: minimum 16 x 16, current 1920 x 1080, maximum 32767 x 32767
XWAYLAND0 connected 1920x1080+0+0 (normal left inverted right x axis y axis) 160mm x 90mm
1920x1080 59.96*+
1440x1080 59.99
1280x1024 59.89
1024x768 59.92
800x600 59.86
640x480 59.38
Display actual display manager :
pi@R4:~ $ cat /etc/X11/default-display-manager
/usr/sbin/lightdm
And its status :
pi@R4:~ $ sudo systemctl status display-manager
● lightdm.service - Light Display Manager
Loaded: loaded (/lib/systemd/system/lightdm.service; indirect; vendor preset: enabled)
Active: failed (Result: exit-code) since Sun 2022-12-18 17:48:29 CET; 1 weeks 6 days ago
Docs: man:lightdm(1)
Process: 975 ExecStartPre=/bin/sh -c [ "$(cat /etc/X11/default-display-manager 2>/dev/null)" = "/usr/sbin/lightdm" ] (code=ex
Process: 977 ExecStart=/usr/sbin/lightdm (code=exited, status=1/FAILURE)
Main PID: 977 (code=exited, status=1/FAILURE)
pi@R4:~ $ sudo systemctl start display-manager
pi@R4:~ $ sudo systemctl status display-manager
● lightdm.service - Light Display Manager
Loaded: loaded (/lib/systemd/system/lightdm.service; indirect; vendor preset: enabled)
Active: activating (auto-restart) (Result: exit-code) since Sat 2022-12-31 18:58:06 CET; 24ms ago
Docs: man:lightdm(1)
Process: 21679 ExecStartPre=/bin/sh -c [ "$(cat /etc/X11/default-display-manager 2>/dev/null)" = "/usr/sbin/lightdm" ] (code=
Process: 21681 ExecStart=/usr/sbin/lightdm (code=exited, status=1/FAILURE)
Main PID: 21681 (code=exited, status=1/FAILURE)
pi@R4:~ $ /usr/sbin/lightdm
Only root can run Light Display Manager. To run as a regular user for testing run with the --test-mode flag.
pi@R4:~ $ /usr/sbin/lightdm --test-mode
Running inside an X server requires Xephyr to be installed but it cannot be found. Please install it or update your PATH environment variable.
pi@R4:~ $ sudo /usr/sbin/lightdm
** (lightdm:25731): WARNING **: 20:11:06.543: Error getting user list from org.freedesktop.Accounts:
GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown:
The name org.freedesktop.Accounts was not provided by any .service files
Try "startx" :
pi@R4:~ $ startx
X.Org X Server 1.20.4
X Protocol Version 11, Revision 0
xorg-server 2:1.20.4-1+rpt4+deb10u5 (https://www.debian.org/support)
Current version of pixman: 0.36.0
Before reporting problems, check http://wiki.x.org
to make sure that you have the latest version.
Markers: (--) probed, (**) from config file, (==) default setting,
(++) from command line, (!!) notice, (II) informational,
(WW) warning, (EE) error, (NI) not implemented, (??) unknown.
(==) Log file: "/home/pi/.local/share/xorg/Xorg.0.log", Time: Sat Dec 31 20:08:15 2022
(==) Using system config directory "/usr/share/X11/xorg.conf.d"
(EE)
Fatal server error:
(EE) parse_vt_settings: Cannot open /dev/tty0 (Permission denied)
(EE)
(EE) Server terminated with error (1). Closing log file.
xinit: giving up
xinit: unable to connect to X server: Connection refused
xinit: server error
Couldn't get a file descriptor referring to the console
Try "systemd-logind" :
pi@R4:/var/log $ sudo systemctl restart systemd-logind
pi@R4:/var/log $ sudo systemctl status systemd-logind
● systemd-logind.service - Login Service
Loaded: loaded (/lib/systemd/system/systemd-logind.service; static; vendor preset: enabled)
Active: active (running) since Sat 2022-12-31 20:20:22 CET; 2s ago
Docs: man:systemd-logind.service(8)
man:logind.conf(5)
https://www.freedesktop.org/wiki/Software/systemd/logind
https://www.freedesktop.org/wiki/Software/systemd/multiseat
Main PID: 26253 (systemd-logind)
Status: "Processing requests..."
Tasks: 1 (limit: 4915)
CGroup: /system.slice/systemd-logind.service
└─26253 /lib/systemd/systemd-logind
Dec 31 20:20:22 R4 systemd[1]: Starting Login Service...
Dec 31 20:20:22 R4 systemd-logind[26253]: New seat seat0.
Dec 31 20:20:22 R4 systemd[1]: Started Login Service.
Dec 31 20:20:22 R4 systemd-logind[26253]: New session 27306 of user pi.
Try "lxpanelctl" :
pi@R4:/var/log $ lxpanelctl restart
Cant connect to display: :0.0
lightdm service : configuration and logs
LightDM description
Configuration file (quite large) :
pi@R4:~ $ cat /etc/lightdm/lightdm.conf | grep logind
# logind-check-graphical = True to on start seats that are marked as graphical by logind
# logind-check-graphical=false
pi@R4:~ $ cat /etc/lightdm/lightdm.conf | grep greeter
greeter-session=pi-greeter
greeter-hide-users=false
pi@R4:~ $ ls -1 /usr/share/xgreeters/
0 lrwxrwxrwx 1 root root 33 Feb 5 2020 lightdm-greeter.desktop -> /etc/alternatives/lightdm-greeter
4 -rw-r--r-- 1 root root 187 Dec 27 2018 lightdm-gtk-greeter.desktop
4 -rw-r--r-- 1 root root 174 Mar 19 2021 pi-greeter.desktop
Display actual configuration :
pi@R4:~ $ lightdm --show-config
[Seat:*]
B greeter-session=pi-greeter
B greeter-hide-users=false
A session-wrapper=/etc/X11/Xsession
B display-setup-script=/usr/share/dispsetup.sh
B autologin-user=pi
Sources:
A /usr/share/lightdm/lightdm.conf.d/01_debian.conf
B /etc/lightdm/lightdm.conf
lightdm command line tool
LightDM offers a command line tool, dm-tool,
which can be used to lock the current seat, switch sessions, etc,
which is useful with 'minimalist' window managers and for testing.
To see a list of available commands, execute:
$ dm-tool --help
pi@R4:~ $ dm-tool switch-to-greeter
Not running inside a display manager, XDG_SEAT_PATH not defined
lightdm as service
System service :
pi@R4:~ $ sudo service lightdm status
● lightdm.service - Light Display Manager
Loaded: loaded (/lib/systemd/system/lightdm.service; indirect; vendor preset: enabled)
Active: failed (Result: exit-code) since Sat 2022-12-31 20:28:00 CET; 15h ago
Docs: man:lightdm(1)
Process: 26694 ExecStartPre=/bin/sh -c [ "$(cat /etc/X11/default-display-manager 2>/dev/null)" = "/usr/sbin/lightdm" ] (code=exited, status=0/SUCCESS)
Process: 26696 ExecStart=/usr/sbin/lightdm (code=exited, status=1/FAILURE)
Main PID: 26696 (code=exited, status=1/FAILURE)
Dec 31 20:28:00 R4 systemd[1]: lightdm.service: Service RestartSec=100ms expired, scheduling restart.
Dec 31 20:28:00 R4 systemd[1]: lightdm.service: Scheduled restart job, restart counter is at 5.
Dec 31 20:28:00 R4 systemd[1]: Stopped Light Display Manager.
Dec 31 20:28:00 R4 systemd[1]: lightdm.service: Start request repeated too quickly.
Dec 31 20:28:00 R4 systemd[1]: lightdm.service: Failed with result 'exit-code'.
Dec 31 20:28:00 R4 systemd[1]: Failed to start Light Display Manager.
Dec 31 20:28:00 R4 systemd[1]: lightdm.service: Triggering OnFailure= dependencies.
pi@R4:~ $ sudo service lightdm start
pi@R4:~ $ sudo service lightdm status
● lightdm.service - Light Display Manager
Loaded: loaded (/lib/systemd/system/lightdm.service; indirect; vendor preset: enabled)
Active: active (running) since Sun 2023-01-01 11:51:29 CET; 14ms ago
Docs: man:lightdm(1)
Process: 11468 ExecStartPre=/bin/sh -c [ "$(cat /etc/X11/default-display-manager 2>/dev/null)" = "/usr/sbin/lightdm" ] (code=exited, status=0/SUCCESS)
Main PID: 11470 (lightdm)
Tasks: 5 (limit: 4915)
CGroup: /system.slice/lightdm.service
├─11470 /usr/sbin/lightdm
└─11480 /usr/lib/xorg/Xorg :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch
Jan 01 11:51:29 R4 systemd[1]: Starting Light Display Manager...
Jan 01 11:51:29 R4 lightdm[11470]: Error getting user list from org.freedesktop.Accounts:
GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.Accounts was not provided by any .service files
Jan 01 11:51:29 R4 systemd[1]: Started Light Display Manager.
... and it crashes in 5 seconds
Dependencies :
pi@R4:~ $ systemctl list-dependencies --reverse lightdm.service
lightdm.service
● └─graphical.target
lightdm log files
Few log files : /var/log/lightdm/lightdm.log and xorg.log and /var/log/Xorg.0.log
pi@R4:~ $ sudo cat /var/log/lightdm/lightdm.log
[+0.62s] DEBUG: XServer 0: Logging to /var/log/lightdm/x-0.log
[+0.62s] DEBUG: XServer 0: Waiting for ready signal from X server :0
[+1.24s] DEBUG: Process 11835 exited with return value 1
[+1.24s] DEBUG: XServer 0: X server stopped
[+1.24s] DEBUG: Releasing VT 7
[+1.24s] DEBUG: XServer 0: Removing X server authority /var/run/lightdm/root/:0
[+1.24s] DEBUG: Seat seat0: Display server stopped
[+1.24s] DEBUG: Seat seat0: Stopping display server, no sessions require it
[+1.24s] DEBUG: Seat seat0: Stopping; greeter display server failed to start
pi@R4:~ $ sudo cat /var/log/lightdm/x-0.log
X.Org X Server 1.20.4
X Protocol Version 11, Revision 0
Markers: (--) probed, (**) from config file, (==) default setting,
(++) from command line, (!!) notice, (II) informational,
(WW) warning, (EE) error, (NI) not implemented, (??) unknown.
(==) Log file: "/var/log/Xorg.0.log", Time: Sun Jan 1 11:54:52 2023
(==) Using system config directory "/usr/share/X11/xorg.conf.d"
(EE)
Fatal server error:
(EE) no screens found (EE)
(EE)
pi@R4:~ $ cat /var/log/Xorg.0.log
[1188290.067]
X.Org X Server 1.20.4
X Protocol Version 11, Revision 0
[1188290.659] (EE) Screen(s) found, but none have a usable configuration.
HDMI reinit
How to reinitialize HDMI without rebooting the RPi
- add hdmi_force_hotplug=1 to /boot/config.txt
You will have to reboot to make that effective (this applies to anything in config.txt).
The display should work now if you plug it in after boot.
However, the resolution may not be set as correctly as it is when booted with the screen attached.
- try tvservice --explicit="DMT 35 HDMI"
This powers on HDMI explicitly with "DMT mode 35" which is 60 HZ at 1280x1024 pixels.
There is also tvservice --off if you've got enough.
For more information try both tvservice --help and looking
tabular listing HDMI modes
pi@R4:~ $ tvservice --help
Usage: tvservice [OPTION]...
-p, --preferred Power on HDMI with preferred settings
-e, --explicit="GROUP MODE DRIVE" Power on HDMI with explicit GROUP (CEA, DMT, CEA_3D_SBS, CEA_3D_TB, CEA_3D_FP, CEA_3D_FS)
MODE (see --modes) and DRIVE (HDMI, DVI)
-t, --ntsc Use NTSC frequency for HDMI mode (e.g. 59.94Hz rather than 60Hz)
-c, --sdtvon="MODE ASPECT [P]" Power on SDTV with MODE (PAL or NTSC) and ASPECT (4:3 14:9 or 16:9) Add P for progressive
-o, --off Power off the display
-m, --modes=GROUP Get supported modes for GROUP (CEA, DMT)
-M, --monitor Monitor HDMI events
-s, --status Get HDMI status
-a, --audio Get supported audio information
-d, --dumpedid <filename> Dump EDID information to file
-j, --json Use JSON format for --modes output
-n, --name Print the device ID from EDID
-l, --list List all attached devices
-v, --device Specify the device to use (see --list)
-h, --help Print this information
Malauradament, no funciona (blank screen) :
pi@R4:~ $ tvservice --explicit="DMT 35 HDMI"
Powering on HDMI with explicit settings (DMT mode 35)
pi@R4:~ $ tvservice -s
state 0x12000a [HDMI DMT (35) RGB full 5:4], 1280x1024 @ 60.00Hz, progressive
pi@R4:~ $ tvservice -l
0 attached device(s), display ID's are :
Interesting command :
pi@R4:~ $ sudo vcdbg log msg
Also modetest
// gcc -o drm-gbm drm-gbm-mod.c -ldrm -lgbm -lEGL -lGL -I/usr/include/libdrm
DRM is sitting on top of the firmware modesetting.
(forums raspberry)
tvservice is an alternate way into the same subsystem.
Using tvservice will cause grief with DRM as DRM has no idea that things have changed - it believes it is master and no one else can change things.
wifi power_save on R4
$ journalctl | grep brcmfmac
Jun 13 22:05:03 R4 kernel: brcmfmac: brcmf_cfg80211_set_power_mgmt: power save enabled
Jun 13 22:10:04 R4 kernel: brcmfmac: brcmf_cfg80211_set_power_mgmt: power save enabled
Jun 13 22:15:03 R4 kernel: brcmfmac: brcmf_cfg80211_set_power_mgmt: power save enabled
Jun 13 22:20:03 R4 kernel: brcmfmac: brcmf_cfg80211_set_power_mgmt: power save enabled
pi@R4:~ $ iw wlan0 get power_save
Power save: on
raspberry stackexchange
a webcam on R4
Vull mesurar quant es triga a fer una foto i quant de espai ocupa ...
Conectem la webcam :
$ dmesg
[377150.104515] usb 1-1.1: new full-speed USB device number 3 using xhci_hcd
[377150.248009] usb 1-1.1: New USB device found, idVendor=046d, idProduct=08da, bcdDevice= 1.00
[377150.248031] usb 1-1.1: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[377150.335146] gspca_main: v2.14.0 registered
[377150.342861] gspca_main: gspca_zc3xx-2.14.0 probing 046d:08da
[377151.768414] input: gspca_zc3xx as /devices/platform/scb/fd500000.pcie/pci0000:00/0000:00:00.0/0000:01:00.0/usb1/1-1/1-1.1/input/input0
[377151.769575] usbcore: registered new interface driver gspca_zc3xx
[377151.854174] usbcore: registered new interface driver snd-usb-audio
$ slog
Jun 13 22:09:05 r4 kernel: [377150.104515] usb 1-1.1: new full-speed USB device number 3 using xhci_hcd
Jun 13 22:09:05 r4 kernel: [377150.248009] usb 1-1.1: New USB device found, idVendor=046d, idProduct=08da, bcdDevice= 1.00
Jun 13 22:09:05 r4 kernel: [377150.248031] usb 1-1.1: New USB device strings: Mfr=0, Product=0, SerialNumber=0
Jun 13 22:09:05 r4 mtp-probe: checking bus 1, device 3: "/sys/devices/platform/scb/fd500000.pcie/pci0000:00/0000:00:00.0/0000:01:00.0/usb1/1-1/1-1.1"
Jun 13 22:09:05 r4 mtp-probe: bus: 1, device: 3 was not an MTP device
Jun 13 22:09:05 r4 kernel: [377150.335146] gspca_main: v2.14.0 registered
Jun 13 22:09:05 r4 kernel: [377150.342861] gspca_main: gspca_zc3xx-2.14.0 probing 046d:08da
Jun 13 22:09:06 r4 kernel: [377151.768414] input: gspca_zc3xx as /devices/platform/scb/fd500000.pcie/pci0000:00/0000:00:00.0/0000:01:00.0/usb1/1-1/1-1.1/input/input0
Jun 13 22:09:06 r4 kernel: [377151.769575] usbcore: registered new interface driver gspca_zc3xx
Jun 13 22:09:06 r4 kernel: [377151.854174] usbcore: registered new interface driver snd-usb-audio
Jun 13 22:09:06 r4 mtp-probe: checking bus 1, device 3: "/sys/devices/platform/scb/fd500000.pcie/pci0000:00/0000:00:00.0/0000:01:00.0/usb1/1-1/1-1.1"
Jun 13 22:09:06 r4 mtp-probe: bus: 1, device: 3 was not an MTP device
Jun 13 22:09:06 r4 systemd-udevd[25586]: Process '/usr/sbin/alsactl -E HOME=/run/alsa restore 2' failed with exit code 99.
Jun 13 22:09:07 r4 systemd-udevd[25581]: Process '/usr/sbin/th-cmd --socket /var/run/thd.socket --passfd --udev' failed with exit code 1.
Actualitzem :
pi@R4:~/python/webcam $ python -m pip install --upgrade pip
Successfully installed pip-20.3.4
pi@R4:~/python/webcam $ python3 -m pip install --upgrade pip
Successfully installed pip-23.1.2
pi@R4:~/python/webcam $ python -m pip install --upgrade opencv-python {python2 falla}
pi@R4:~/python/webcam $ python3 -m pip install --upgrade opencv-python
Installing collected packages: numpy, opencv-python
Successfully installed numpy-1.21.6 opencv-python-4.7.0.72
pi@R4:~/python/webcam $ sudo apt-get update
Que tenim ?
pi@R4:~/python/webcam $ v4l2-ctl --list-devices
bcm2835-codec-decode (platform:bcm2835-codec):
/dev/video10
/dev/video11
/dev/video12
/dev/video18
bcm2835-isp (platform:bcm2835-isp):
/dev/video13
/dev/video14
/dev/video15
/dev/video16
Cannot open device /dev/video0, exiting.
Lets run the code :
pi@R4:~/python/webcam $ ./1_fer_foto.py
### NUMPY version I have is 1.21.6
### CV2 version I have is 4.7.0
ImportError: libcblas.so.3: cannot open shared object file: No such file or directory
--> sudo apt-get install libcblas-dev --> sudo apt-get install libatlas-base-dev
[ WARN:0@0.022] global cap_v4l.cpp:982 open VIDEOIO(V4L2:/dev/video0): can't open camera by index
[ERROR:0@0.025] global obsensor_uvc_stream_channel.cpp:156 getStreamChannelGroup Camera index out of range
--> cap = cv2.VideoCapture(-1)
[ WARN:0@0.022] global cap_v4l.cpp:969 open VIDEOIO(V4L2): can't find camera device
[ERROR:0@0.025] global obsensor_uvc_stream_channel.cpp:156 getStreamChannelGroup Camera index out of range
cap.set( cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 160 ) # 1280 1024 800 640 320 ?160
AttributeError: module 'cv2' has no attribute 'cv'
Comandament per veu
Amazon Alexa, Apple Siri, Google Assistant,
Em mola dir-li una cançó i que me la posi. Pero no la vull de Spotify, sino del meu disc de 2 TB.
Aixo em porta a un "comandament per veu" mes generic, propi.
Que jo li digui una comanda, ell la entengui, i engegui una tasca que jo pugui programar.
Llegeixo :
Si os gusta automatizar tareas en casa,
podéis probar a hacerlo con Home Assistant,
un software para automatizar tareas que permite integrar Alexa, el asistente de Google o HomeKit.
Alexa es la que mejor funciona con este software, pero también es posible usar los otros.
Para usarlo, es necesario comprar una Raspberry Pi 3 Model B+, que es la que hace de centralita.
adslzone.net
Picovoice/porcupine
On-device wake word detection powered by deep learning :
github
Boot from USB disk
Editar /boot/config.txt i posar
root=/dev/sda
per
root=/dev/sdb
The Raspberry Pi 3B+ and CM3+ support USB mass storage boot out of the box.
After preparing the storage device, connect the drive to the Raspberry Pi and power up the Pi.
Be aware of the extra USB power usage from the external drive.
After five to ten seconds, the Raspberry Pi should begin booting and show the rainbow splash screen on an attached display.
Make sure that you do not have an SD card inserted in the Pi, since if you do, it will boot from that first.
How to prepare the USK disk ?
This is the same procedure as for
SD cards.
docu
Cómo hacer que la Raspberry Pi 4 arranque desde un SSD o pen drive USB
Steps :
- arrancar la Raspberry Pi desde la micro SD de manera normal
- actualizar el sistema operativo : "sudo apt update" + "sudo apt full-upgrade"
- "sudo nano /etc/default/rpi-eeprom-update" : cambia el valor «critical» de "RELEASE_STATUS" por «beta» y pulsa CTRL + X para salir y guardar
- instalar el bootloader beta : "sudo rpi-eeprom-update -d -f /lib/firmware/raspberrypi/bootloader/beta/pieeprom-2020-05-15.bin"
- reboot y verificar version del bootloader con "vcgencmd bootloader_version"
- crear SSD o pen drive USB con Raspbian (se puede usar "SD Copier")
hardzone
Moving to a bigger SD
Raspberry PI tricks: migrating to larger SD card with Windows
- required software : windows : Win32DiskImager
- insert "small" SD
- create "my_sd.img"
- insert "big" SD
- write IMG on it
- boot "big" SD
- sudo raspi-config
- 7 - Advanced Options
- A1 - Expand Filesystem
peppe8o
See canvi SD [***]
Software, shells and configurations in all my Raspian's
El programari que hi tinc a tots els Raspbian es :
PiZero R3 R4 mars
.
iwgetid = get wifi name belkin a55 a55 a55
.
.bash_aliases . . . +
.
engegades.log (1) (5) (1) +
.
IP fixe (4) 192.168.1.222 192.168.1.123 192.168.1.200 .
.
missatge SSHD (3) + + + -
.
mail (to read cron errors) + + + +
.
crontab (2) + + + +
.
1_netejar.sh ? ? ? ? 2.a
.
backup using email + + + + 2.b
.
msg_a_tg (boot/kron) + + + + 2.c
.
wifi_wd + temperatura + ping + + + - 2.d
.
enviar HTML a Tinet
+ + + - 2.e
.
ping_multiple_gas2 (6) . - - +
.
wd_a_byet.py (7) + - - -
.
Detalls :
Darrers shells
Usualment son
- (+) 1_netejar.sh
- (+) fer_backup.sh
- enviar_html_a_tinet.py
- msg_a_tg.sh
- wifi_wd.sh
1_netejar.sh = netejar el subdirectori "logs" de fitxers de log
pi@pi0:~/logs $ cat 1_netejar.sh
#!/bin/bash
# netejar el directori de "logs"
# actual logs are moved to "oldies" subdir, where previous file is deleted
# new log file is created, consisting of just one line : the filename and a timestamp
# v 1.0.a - 20201210 - script to be rur once a month from cron
# 1.0.b - 20210315 - create "oldies" dir
# 1.0.c - 20211209 - ignore error msg if subdir exists
myT=$(date +"%H:%M:%S")
myD=$(date +"%d/%m/%Y")
myS=$myD,$myT
log_FN="/home/pi/logs/1_netejar.log" # define my log filename
echo ">>> clean logs - v 1.0.b - "$myS >> $log_FN # add one line
function doInit {
szFN=$1
# echo ">>> Lets init "$szFN --- debug only
szOld="./oldies/"$szFN".old" # oldies are saved into sub-directory
rm -f $szOld # remove previous old file
mv $szFN $szOld # save actual log with ".old" sufix
szInit="*** $myS *** $szFN ***" # set creation timestamp in log file
echo "$szInit" > $szFN # create an empty log file (just 1 line, name and date)
return 0
} ; # doInit
mkdir /home/pi/logs/oldies 2> /dev/null # create "oldies" subdir to save previous logs, ignore "existing" msg
doInit bot_service.log
# doInit engegades.log
doInit envia_ip.log
doInit enviar_html_a_tinet.log
doInit fer_backup.log
doInit msg_a_tg.log
doInit my_wd.log
doInit oled.log
doInit pwm_start.log
doInit rpz_start.log
doInit send_telegram.log
doInit wd_a_byet.log
doInit wifi_wd.log
exit 0
fer_backup.sh = salvar fitxers amb un email
pi@R4:~/eines/backup $
cat fer_backup.sh
#!/bin/bash
# Passos del algorisme :
# 1 - esborrem el fitxer tgz anterior
# 2 - comprimim els fitxers en el tgz
# 3 - enviem el tgz per email
# ---
# Versions :
# 1.a 20190327 - enviem a yandex
# 1.b - esborrem contingut directori abans de tot
# 1.c - comptar el nombre de fitxers copiats
# 1.d - millorar missatges, SAG 20191015
# 1.e - 2 destinataris
# 1.f - copia de ESP a MARS i adaptacio directoris, destinataris, ...
# 1.g - filtre mail.log
# 1.h - adaptacio ODIN
# 1.i - canviar nom a JPEG
# 2.a - dont copy files to keep directory, use MUTT, use TINET gateway
# 2.b - verify file exists
# 2.c - trace job start
# 2.d - proper date format
# 3.a - add CRON programation
# 3.c - list of actually sent files into Body
# 3.d - say how many files are sent versus filenames in list
# 3.e - redir mutt stdout and stderr to log
# 3.f - set logs as relative
#
# Debug
# ping gmail-smtp-in.l.google.com
# ping mx.yandex.ru
#
# error 2020 : May 5 14:22:20 odin sSMTP[2572]:
# 552 5.7.0 message content and attachment content guidelines. h10sm3014356wrv.29 - gsmtp
# entrar per t1net -
cfg
#
szVer="v 3.f"
myBasePath="/home/pi"
myPath=$myBasePath"/eines/backup"
myCronFile=$myPath"/cron_values.txt"
fnIN="$myPath/llista_fitxers.txt"
fnOUT="$myPath/sortida.tar"
if [[ ! -f $fnIN ]]
then
echo "--- $fnIN does not exist on your filesystem."
exit 1
fi
fnLOG=$myBasePath"/logs/fer_backup.log"
szHN=$HOSTNAME
fn2Send="pic_"$szHN"_tar.jpg"
szDESTI="manel.carnero@yandex.com neus.bertolin@gmx.com sveta.glojova@aol.com"
szT=$(date +%R)
szD=$(date +"%d/%m/%Y") # short date, 4 digit year, day before month
szDeit=$szD,$szT
szTitol="+++ $szDeit +++ ($szHN) +++ ($0) +++ ($szVer) +++ Backup files from ($fnIN) sent to ($szDESTI)."
szBody="* $szDeit * [$szHN] * ($0) ($szVer) backup using mutt *"
echo -e "\n$szTitol" &>> $fnLOG
echo "(0) --- create $myCronFile" &>> $fnLOG
echo "+++ ($szDeit) +++ cron values +++" &> $myCronFile
echo "+++ ($szDeit) +++ crontab +++" &>> $myCronFile
crontab -l &>> $myCronFile
echo "+++ ($szDeit) +++ daily +++" &>> $myCronFile
ls -al /etc/cron.daily/ &>> $myCronFile
echo "+++ ($szDeit) +++ hourly +++" &>> $myCronFile
ls -al /etc/cron.hourly &>> $myCronFile
echo "+++ ($szDeit) +++ monthly +++" &>> $myCronFile
ls -al /etc/cron.monthly/ &>> $myCronFile
echo "+++ ($szDeit) +++ weekly +++" &>> $myCronFile
ls -al /etc/cron.weekly/ &>> $myCronFile
echo "(1) --- esborrar fitxers vells" &>> $fnLOG
rm -f $fnOUT &>> $fnLOG
rm -f $fn2Send &>> $fnLOG
echo "(2) --- TAR fitxers nous" &>> $fnLOG
cnt=0
linies=0
while read linia; do
linies=$(($linies+1))
echo "+++ Posem fitxer" $linia &>> $fnLOG
if [ -f "$linia" ]; then
cnt=$(($cnt+1))
echo "+++ ($cnt) +++ $linia exists" &>> $fnLOG
tar -rf $fnOUT $linia &>> $fnLOG
szBody="${szBody}\n${cnt}-${linia}"
else
echo "--- $linia does not exist" &>> $fnLOG
fi
done < $fnIN
szBody="${szBody}\n* Hem enviat ${cnt} fitxers de ${linies} llistats al fitxer *"
echo "(3) --- rename de ($fnOUT) a ($fn2Send)" &>> $fnLOG
mv $fnOUT $fn2Send
szSubject="+++ $szDeit +++ ($szHN) +++ ($0) +++ ($szVer) +++ Backup ($cnt/$linies) files from ($fnIN)."
echo "(4) --- subject --- $szSubject" &>> $fnLOG
echo -e "(5) --- body --- $szBody" &>> $fnLOG
echo "(6) --- enviem fitxer ($fn2Send) a ($szDESTI)" &>> $fnLOG
# normal mutt
echo -e "$szBody" | mutt -s "$szSubject" -a "$fn2Send" -- $szDESTI &>> $fnLOG
# debug mutt : see ~/.muttdebug0
# echo -e "$szBody" | mutt -d 5 -s "$szSubject" -a "$fn2Send" -- $szDESTI
rv=$?
echo "$szDeit MAIL return code" $rv &>> $fnLOG
# szFiltre="tinet.cat"
# echo "$szDeit Que hi ha de ($szFiltre) al LOG de MAIL :" >> $fnLOG
# cat /var/log/mail.log | grep $szFiltre >> $fnLOG
# tail -n 30 /var/log/mail.log | grep "yandex.com" >> $fnLOG
exit 0
webmin
- append the official Webmin Debian repository to /etc/apt/sources.list :
vim /etc/apt/sources.list
deb https://download.webmin.com/download/repository sarge contrib
- get the package information from the Webmin Debian repository :
apt update
- add the Webmin key to avoid the packages change over the network :
cd /tmp
wget https://download.webmin.com/jcameron-key.asc
apt-key add jcameron-key.asc
- install webmin : "apt-get install webmin" - some pre-reqs shall fail
- "apt --fix-broken install" - install missing dependencies
- "apt-get install webmin"
- access webmin on Raspbian
varhowto
Pending
- dmesg full of "broken atomic modeset userspace detected, disabling atomic"
- /var/log/messages full of wlan0 text "cfg80211: World regulatory domain updated:"
Also, dmesg has "brcmf_cfg80211_reg_notifier: not a ISO3166 code"
"sudo raspi-config" + "4 = Internationalisation Options" + "I4 = Change Wi-Fi Country"; "ES" = "Wifi country set to ES"; reboot
pi@odin:~ $ iwlist wlan0 channel(/freq)
wlan0 13 channels in total; available frequencies :
Channel 01 : 2.412 GHz
Channel 02 : 2.417 GHz
Channel 03 : 2.422 GHz
Channel 04 : 2.427 GHz
Channel 05 : 2.432 GHz
Channel 06 : 2.437 GHz
Channel 07 : 2.442 GHz
Channel 08 : 2.447 GHz
Channel 09 : 2.452 GHz
Channel 10 : 2.457 GHz
Channel 11 : 2.462 GHz
Channel 12 : 2.467 GHz
Channel 13 : 2.472 GHz
Current Frequency:2.462 GHz (Channel 11)
També
pi@odin:~ $ iw reg get
country ES: DFS-ETSI
(2400 - 2483 @ 40), (N/A, 20), (N/A)
(5150 - 5250 @ 80), (N/A, 23), (N/A), NO-OUTDOOR
(5250 - 5350 @ 80), (N/A, 20), (0 ms), NO-OUTDOOR, DFS
(5470 - 5725 @ 160), (N/A, 26), (0 ms), DFS
(57000 - 66000 @ 2160), (N/A, 40), (N/A)
Snaps
Snaps are applications packaged with all their dependencies to run on all popular Linux distributions from a single build.
They update automatically and roll back gracefully.
Snaps are discoverable and installable from the
Snap Store, an app store with an audience of millions.
snapcraft
snaps and filesystem
Tu creus que aixo es normal ?
nicolau@mars:~$ df -h
Filesystem Size Used Avail Use% Mounted on
udev 5.8G 0 5.8G 0% /dev
tmpfs 1.2G 2.0M 1.2G 1% /run
/dev/sda1 229G 156G 62G 72% /
tmpfs 5.9G 114M 5.8G 2% /dev/shm
tmpfs 5.0M 4.0K 5.0M 1% /run/lock
tmpfs 5.9G 0 5.9G 0% /sys/fs/cgroup
/dev/loop2 768K 768K 0 100% /snap/gnome-characters/741
/dev/loop0 323M 323M 0 100% /snap/wine-platform-6-stable/14
/dev/loop3 347M 347M 0 100% /snap/gnome-3-38-2004/115
/dev/loop1 64M 64M 0 100% /snap/core20/1695
/dev/loop4 348M 348M 0 100% /snap/wine-platform-runtime/319
/dev/loop6 1.5M 1.5M 0 100% /snap/gnome-system-monitor/181
/dev/loop5 363M 363M 0 100% /snap/telegram-desktop/4312
/dev/loop7 142M 142M 0 100% /snap/docker/2285
/dev/loop8 71M 71M 0 100% /snap/core22/275
/dev/loop9 115M 115M 0 100% /snap/core/14056
/dev/loop10 2.7M 2.7M 0 100% /snap/gnome-system-monitor/178
/dev/loop11 163M 163M 0 100% /snap/gnome-3-28-1804/145
/dev/loop12 45M 45M 0 100% /snap/filezilla/17
/dev/loop14 512K 512K 0 100% /snap/gnome-characters/781
/dev/loop13 128K 128K 0 100% /snap/bare/5
/dev/loop15 370M 370M 0 100% /snap/telegram-desktop/4353
/dev/loop18 415M 415M 0 100% /snap/gnome-42-2204/29
/dev/loop19 9.7M 9.7M 0 100% /snap/htop/3414
/dev/loop16 56M 56M 0 100% /snap/cups/836
/dev/loop17 9.7M 9.7M 0 100% /snap/htop/3417
/dev/loop20 146M 146M 0 100% /snap/chromium/2221
/dev/loop21 768K 768K 0 100% /snap/gnome-logs/115
/dev/loop23 304M 304M 0 100% /snap/wine-platform-5-stable/18
/dev/loop22 219M 219M 0 100% /snap/gnome-3-34-1804/77
/dev/loop26 304M 304M 0 100% /snap/wine-platform-5-stable/16
/dev/loop24 2.5M 2.5M 0 100% /snap/gnome-calculator/884
/dev/loop25 82M 82M 0 100% /snap/gtk-common-themes/1534
/dev/loop27 640K 640K 0 100% /snap/gnome-logs/112
/dev/loop28 348M 348M 0 100% /snap/wine-platform-runtime/320
/dev/loop29 347M 347M 0 100% /snap/gnome-3-38-2004/119
/dev/loop30 56M 56M 0 100% /snap/core18/2632
/dev/loop31 219M 219M 0 100% /snap/gnome-3-34-1804/72
tmpfs 1.2G 20K 1.2G 1% /run/user/121
/dev/loop32 2.7M 2.7M 0 100% /snap/gnome-calculator/920
/dev/loop33 146M 146M 0 100% /snap/chromium/2193
/dev/loop34 73M 73M 0 100% /snap/core22/310
/dev/loop35 64M 64M 0 100% /snap/core20/1634
/dev/loop36 56M 56M 0 100% /snap/core18/2620
/dev/loop37 115M 115M 0 100% /snap/core/13886
/dev/loop38 447M 447M 0 100% /snap/gnome-42-2204/44
/dev/loop39 92M 92M 0 100% /snap/gtk-common-themes/1535
/dev/loop40 323M 323M 0 100% /snap/wine-platform-6-stable/19
/dev/loop41 261M 261M 0 100% /snap/kde-frameworks-5-core18/32
/dev/loop42 119M 119M 0 100% /snap/docker/1779
/dev/loop43 165M 165M 0 100% /snap/gnome-3-28-1804/161
tmpfs 1.2G 32K 1.2G 1% /run/user/1000
Recovery mode
On Raspbian boot, we can read For recovery mode, hold "Shift"
What does it do ?
Provided that you are ready and press the Shift key, you will enter a recovery partition.
The recovery partition allows you to start again, easily, with another copy of Raspian or with an alternative OS.
url
Troubleshooting
Serial port logging
If you want to access the Pi's serial console, you have to connect the Raspberry UART to a PC :
- buy a "serial-to-USB" converter, as this Adafruit, chip CP2102 or
tiendatec,
"cable conversor USB a serie RS232 UART TTL 3.3V"
PL2303TA
Is your USB to serial dongle TTL at 3.3v?
Conversor USB a señales RS232 TTL
Lleva integrado un cable con pines tipo Dupont hembra, para conectar directamente al dispositivo a controlar.
La distribución de pines es:
- Rojo: +5V
- Negro: GND
- Blanco: RXD
- Verde: TXD
- connect to GPIO : (read serial connection)
- black to pin 6, GND
- white to pin 8, GPIO 14 (UART TX)
- green to pin 10, GPIO 15 (UART RX)
use "sudo raspi-gpio get" to check TX-RX is really on GPIO 14-15 or not, if you can boot the Raspberry
- connect USB to PC and
nicolau@mars:~$ ls /dev | grep usb -> note the tty.usbserial- and cu.usbserial- numbers in there
nicolau@mars:/dev$ ls /dev/ttyU*
0 crw-rw---- 1 nicolau dialout 188, 0 Mar 29 17:18 /dev/ttyUSB0
often the device is called /dev/ttyUSB0 - run sudo dmesg after plugging in and looking for hints on what the device is called.
If you get "cannot open /dev/ttyUSB3: Device or resource busy error", you have two options:
askubuntu
- run "minicom" or "screen"
nicolau@mars:~$ minicom -b 115200 -D /dev/tty.usbserial-0001
nicolau@mars:~$ sudo minicom -b 115200 -D /dev/ttyUSB0
nicolau@mars:~$ screen /dev/tty.usbserial-0001 115200
jeff geerling
See /boot/config.txt
# Albert, 20160704 - USB current problems # Sebas, 20220329
usb_max_current=1
hdmi_force_hotplug=1
enable_uart=1
See /boot/cmdline.txt
dwc_olg.lpm_enable=0 console=tty1 console=serial0,115200 root=/dev/mmcblk0p2
rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait
{20220329} nicolau@mars:/media/nicolau/boot$ cat cmdline.txt
console=serial0,115200 console=tty1 root=PARTUUID=0a7c757a-02 rootfstype=ext4 fsck.repair=yes rootwait
Remove
quiet # surpresses boot log
plymouth.ignore-serial-consoles
So we have
pi@R4:/boot $ cat cmdline.txt
console=serial0,115200 console=tty1 root=/dev/mmcblk0p7 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait splash
nicolau@mars:~$ tail -f /var/log/syslog
Mar 29 13:37:08 mars kernel: [13633.927367] usb 3-3: new full-speed USB device number 2 using ohci-pci
Mar 29 13:37:08 mars kernel: [13634.122478] usb 3-3: New USB device found, idVendor=067b, idProduct=2303, bcdDevice= 4.00
Mar 29 13:37:08 mars kernel: [13634.122484] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=0
Mar 29 13:37:08 mars kernel: [13634.122487] usb 3-3: Product: USB-Serial Controller
Mar 29 13:37:08 mars kernel: [13634.122490] usb 3-3: Manufacturer: Prolific Technology Inc.
Mar 29 13:37:08 mars mtp-probe: checking bus 3, device 2: "/sys/devices/pci0000:00/0000:00:12.0/usb3/3-3"
Mar 29 13:37:08 mars mtp-probe: bus: 3, device: 2 was not an MTP device
Mar 29 13:37:08 mars kernel: [13634.582822] usbcore: registered new interface driver usbserial_generic
Mar 29 13:37:08 mars kernel: [13634.582840] usbserial: USB Serial support registered for generic
Mar 29 13:37:08 mars kernel: [13634.585747] usbcore: registered new interface driver pl2303
Mar 29 13:37:08 mars kernel: [13634.585947] usbserial: USB Serial support registered for pl2303
Mar 29 13:37:08 mars kernel: [13634.585977] pl2303 3-3:1.0: pl2303 converter detected
Mar 29 13:37:08 mars kernel: [13634.608758] usb 3-3: pl2303 converter now attached to ttyUSB0
Mar 29 13:37:08 mars upowerd[1176]: unhandled action 'bind' on /sys/devices/pci0000:00/0000:00:12.0/usb3/3-3
Mar 29 13:37:08 mars snapd[1131]: hotplug.go:199: hotplug device add event ignored, enable experimental.hotplug
Mar 29 13:37:08 mars upowerd[1176]: unhandled action 'bind' on /sys/devices/pci0000:00/0000:00:12.0/usb3/3-3/3-3:1.0
And
nicolau@mars:~$ dmesg
[13633.927367] usb 3-3: new full-speed USB device number 2 using ohci-pci
[13634.122478] usb 3-3: New USB device found, idVendor=067b, idProduct=2303, bcdDevice= 4.00
[13634.122484] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[13634.122487] usb 3-3: Product: USB-Serial Controller
[13634.122490] usb 3-3: Manufacturer: Prolific Technology Inc.
[13634.582822] usbcore: registered new interface driver usbserial_generic
[13634.582840] usbserial: USB Serial support registered for generic
[13634.585747] usbcore: registered new interface driver pl2303
[13634.585947] usbserial: USB Serial support registered for pl2303
[13634.585977] pl2303 3-3:1.0: pl2303 converter detected
[13634.608758] usb 3-3: pl2303 converter now attached to ttyUSB0
And
nicolau@mars:~$ minicom -b 115200 -D /dev/ttyUSB0
Welcome to minicom 2.7.1
OPTIONS: I18n
Compiled on Aug 13 2017, 15:25:34.
Port /dev/ttyUSB0, 13:37:08
Press CTRL-A Z for help on special keys
Using "CTRL" + "A", then "Z", we get
+-------------------------------------------------------------------+
| Minicom Command Summary |
| |
| Commands can be called by CTRL-A &key> |
| |
| Main Functions Other Functions |
| |
| Dialing directory..D run script (Go)....G | Clear Screen.......C |
| Send files.........S Receive files......R | cOnfigure Minicom..O |
| comm Parameters....P Add linefeed.......A | Suspend minicom....J |
| Capture on/off.....L Hangup.............H | eXit and reset.....X |
| send break.........F initialize Modem...M | Quit with no reset.Q |
| Terminal settings..T run Kermit.........K | Cursor key mode....I |
| lineWrap on/off....W local Echo on/off..E | Help screen........Z |
| Paste file.........Y Timestamp toggle...N | scroll Back........B |
| Add Carriage Ret...U |
| |
| Select function or press Enter for none. |
+-------------------------------------------------------------------+
Another way
nicolau@mars:~$ sudo minicom -s
+-----[configuration]------+
| Filenames and paths |
| File transfer protocols |
| Serial port setup |
| Modem and dialing |
| Screen and keyboard |
| Save setup as dfl |
| Save setup as.. |
| Exit |
| Exit from Minicom |
+--------------------------+
Funciona al MARS 20220823, to display "boot" log (only)
Using screen, after "sudo apt install screen" :
nicolau@mars:~$ screen /dev/ttyUSB0 115200
Al MARS no em funciona el screen
Serial port logging URLs
Links
- Raspberry homepage ,
forums [***] -
Dougie Lawson : Twitter ,
Raspbeeypi Forums
- Raspberry Wikipedia
- NOOBS = New Out Of Box Software
- RPI hub and
R-Pi Troubleshooting
- semaphore video and
tools
- toolkit based on node, for nodejs apps, makes life easier
- deep document
- si volem millorar el wifi 4 dBi : TP-LINK
TL-WN722N : 150 Mbps IEEE 802.11n
- acces via SSH sense
pwd.
Try "$ ssh -vvv 192.168.0.13". Use "sudo netstat -tlpn"
- WhatsApp pwd recovery tool
- Venden una cámara específicamente para la raspberry, que además es barata:
module v2.
Seguramente tendrá buenas APIs pero no sé si para nodejs.
- per dibuixar circuits : digikey
- projecte "base" de node : cdt
- complete "semaphore" code
- similar project : home automation
- Raspberry Pi Zero + Pi Camera :
self driving car,
formulaPi.com, robotics PiBorg.org
- HW similar :
- 20170228 :
Raspberry Pi Zero W,
a new variant of Raspberry Pi Zero with wireless LAN and Bluetooth, priced at only $10.
- Chess Board:
play against Raspberry Pi with real pieces (uses LEDs)
- blog for tech questions :
StackOveflow, as
tcp problem
Also
raspberry StackExchange {***}
- Android on Raspberry Pi 3
- Maker.pro : interesting projects
- millorar "top" - htop
- apt-cache search htop
- sudo apt-get install htop
- sudo apt-get autoremove
- eina Ethernet - ethtool
- $ sudo apt-get update ; sovint
- $ sudo apt-get install ethtool
- $ sudo apt-get autoremove
- eina Benchmark :
- $ sudo apt-get install sysbench
- $ sysbench --test=cpu --num-threads=4 --cpu-max-prime=9999 run
- amazon ABOX Raspberry Pi 3 B+ Starter Kit" 68 €
- botigues components :
- cosetes de python pel Raspberry :
- robot
- boston dynamics robot
The mini ‘Spot Micro’ bot rocks a three-axis angle command/body pose control mode via keyboard
Requirements :
- Servo control board: PCA9685, controlled via I2C
- Servos: 12 × PDI-HV5523MG
- ferralla
- pantalla i2c
- saleae logic analyzer
- jumper kit
- muestrario resistors
- USB power
- CPU status displaying
LED cube
- FTP
- projectes
- pantalla 3,5 polsades
- Aliexpress AIDA64, 19 €, 480x320
- Amazon SOHDY, 19 €, 800x480 (?) -> 480x320 - compte : SPI
- Amazon CUQI, 42 €, 1024x600
- Amazon Generique 7CGQ-852 , 18€, 1024x600, 7 polsades,
signal : mini HDMI, power : micro USB
- antenes per Raspberry :
NRF24L01 + PA + LNA + SMA antenna
- Specs :
- 3 piezas - 14 €
- NRF24L01 es un transceptor de radio de solo chip para banda ISM de 2,4-2,5 GHz
- comsum : 115 mA
- interfaz 4 pines serie SPI
- parámetros configurables : canal de frecuencia (125 canales seleccionables), potencia de salida, y la velocidad de datos (250kbps, 1 Mbps, 2 Mbps)
- codi Arduino + Raspberry
- llibreria python pynrf24
- high speed driver - sample with "from RF24 import *" {Irina}
- proves al "odin" :
conexio a antena NRF24
- esquemes ;
R4 reduits :
- Raspberry pico -
buy it : 4 $
pi pico W, 6 $
The Raspberry Pi Pico W could replace many Raspberry Pi Zero W based projects, such as low powered robots and data collection projects.
If all we are doing is collecting temperature / humidity and air pressure data, do we need a Linux OS ?
- gran update : "sudo rpi-update"
- ALL boot problems and solutions
- kodi
Kodi is a free and open source media player application developed by the Kodi Foundation, a non-profit technology consortium.
Kodi is available for multiple operating-systems and hardware platforms, featuring a 10-foot user interface for use with televisions and remote controls.
It allows users to play and view most videos, music, podcasts, and other digital media files from local and network storage media and the internet.
- Raspberry Pi OS ya está disponible en 64 bits
- building a Tor proxy
with a Raspberry Pi
- use guacamole for remote admin using a browser
Again :
Creating a Remote Desktop Web Gateway
on Raspberry Pi with Apache Guacamole
- boot Pi 4 from SSD
- remote access
- bootable Raspbian images by Hexxeh vs "official"
Raspberry Pi OS (previously called Raspbian)
- Ubuntu on Rspi
- MQTT on Raspberry
- RASPAP : feature-rich wireless router software, simple AP setup & WiFi management for Debian-based devices -
documentation,
github