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
Raspberry homepage + forums + qq

Raspberry 3 model B
Specs

El Raspberry Pi ...

Some webs :

Mine has :

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

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 :

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

NOOBS setup

  1. download NOOBS into W500 {c:\temp\rsp3\NOOBS_v3_2.zip} - see "gDrive(gruta)"

  2. unzip the file into "C:\temp\rsp3\NOOBS_v3_2"

  3. connect the SD card to W500 using square USB adapter {not flat}

  4. set up your SD card :

    1. clear the SD : C:\> format /fs:fat32 f: - Raspberry Pi can only read FAT32 volumes

    2. 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

    3. see SD formatter for cards under 32 GB

    4. 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"

    5. 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

  1. conecta SSD
  2. bota raspbian
  3. sudo parted /dev/sda
  4. fer 1 sola particio que ocupi tot el disc
  5. comanda : ?
  6. fer rsync

Amunt! Top Amunt!
Instal.lació
Compra

El kit de Diotronic (87,45 €) inclou

Engegada inicial

  1. insert SD card into slot
  2. connect USB keyboard and mouse
  3. connect HDMI into monitor
  4. connect Ethernet cable to router (or use wifi)
  5. plugin power supply to boot Raspberry Pi
Configuració del "raspall"

  1. NOOBS instala Debian / Raspbian
  2. hostname := "raspall" ;
  3. default user = "pi", default password = "raspberry" ;
  4. passwd pi : u = "pi", p = "bcn10" ; u2 = "sag", p2 = "<ya_3>2016" ;
  5. 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

  1. start raspi-config with: sudo raspi-config
  2. go into System Options > Wireless LAN
  3. type your SSID and your password
  4. 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 :

  1. write a Raspbian image onto the SD card
  2. open the SD card on Ubuntu to see the small FAT32 partition
  3. create a "ssh.txt" file with any contents
  4. 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

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 :

/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 :

  1. enable trace : sudo echo 0xffff > /sys/module/uvcvideo/parameters/trace
  2. reproduce the problem - driver prints message to kernel log
  3. disable trace : sudo echo 0 > /sys/module/uvcvideo/parameters/trace
  4. 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
BCM notation Raspberry 40-pin GPIO connector Raspberry 40-pin GPIO connector

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


Amunt! Top Amunt!
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 :

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.

  1. "sudo su -" {no cal si posem "sudo" a cada comanda}
  2. edit crontab : sudo crontab -e
  3. 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
  4. output and errors are sent using mail to this user
  5. view scheduled tasks : sudo crontab -l
  6. 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/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

Amunt! Top Amunt!
SAG's "odin" hw & sw
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

  1. extreu img de la sd vella a disc laptop (HD Raw Copy Tool)
  2. graba imatge a sd nova
  3. 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

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 :

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"

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

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

Amunt! Top Amunt!
Projectes amb el Raspberry

Amb el Raspberry hem fer projectes macos :

Projectes pel futur

Amb el Raspberry volem fer altres projectes :


Amunt! Top Amunt!
LED amb python i node
led pinout transistor aillament

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) :

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


Amunt! Top Amunt!
Semàfor
SSR

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

esquema

Cablejat

Cables que surten del GPIO del Raspberry cap a la breadboard/protoboard :

Software

Switch a light on/off using your smartphone, using node.js ! {help.privateeyepi@gmail.com}

  1. sudo apt-get update {sempre}

  2. sudo apt-get upgrade {delicat, no fer}

  3. sudo apt-get install npm

    pi@raspberrypi-llovet:~ $ npm -v 1.4.21

  4. 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)

  5. 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 $

  6. 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"

  7. 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 $

  8. 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" }

  9. 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]

  10. 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 $

  11. start application : node webgpio.js

    pi@raspberrypi-llovet:~/semafor $ node webgpio.js Server running at http://192.168.1.123/

  12. 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

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

  1. sudo apt-get update ; sovint
  2. sudo apt-get install libhighgui2.4 libopencv-imgproc2.4 libopencv-core2.4 python-opencv
  3. sudo apt-get install python-opencv
  4. 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 :

[]

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
simbol Wifi

Sempre hem de fer, en aquest ordre :

  1. apagar el Raspall
  2. conectar el teclat USB-A al Raspall
  3. conectar el ratolí USB-A al Raspall
  4. conectar la pantalla HDMI al Raspall
  5. engegar el Raspall
  6. en 1 minut, ha de sortir un quadre de vora un pam quadrat amb tots els colors
  7. 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 :

Objectiu : separar les dues xarxes i posar una clau de pas senzilla.

aire condicionat

Dades :

Wi-Fi interface :

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


Amunt! Top Amunt!
RMTC - remote control
SC107 v2

*** 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 :

  1. posem "sag" a sudoers

    pi@odin:~ $ sudo usermod -aG sudo sag

  2. posem el sistema al dia - fer-ho sovint

    sag@odin:~ $ sudo apt-get update

  3. 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:~ $

  4. instalem els requisits :

    sag@odin:~ $ cd Raspberry-Pi-Simple-Web-GPIO-GUI/ sag@odin:~/Raspberry-Pi-Simple-Web-GPIO-GUI $ npm install

  5. 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

  6. 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

  7. 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]

  8. 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

  9. 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

  10. 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

  11. 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
  1. el client engega un browser al seu telefon
  2. que està conectat a la wifi "GAS2"
  3. que és proporcionada per el router ZyXel
  4. i està conectat a la meva antena "NanoBeam M5"
  5. que es conecta a la antena "Rocket 5" del Campanar
  6. que te un enllaç de sues antenes "LiteBeam AC" amb Can Sostres
  7. on hi ha un router de Fibra Òptica de Timofònica
  8. que ens porta a Internet
  9. on està conectat el meu router de Fibra Òptica
  10. que proporciona la xarxa wifi "enxaneta"
  11. on es conecta el Raspberry "odin"
  12. que te un sistema operatiu "Raspbian"
  13. on s'executa una APP escrita en "nodeJS"
  14. que permet manegar els pins GPIO
  15. on hi ha un transistor SC107
  16. que manega un SSR CX205D5 (AC load)
  17. que te com a càrrega una bombeta incandescent de 50 watts
cable pla
RMTC links

Amunt! Top Amunt!
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

  1. 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:~ $

  2. instalem els requisits :

    sag@odin:~ $ cd express-sendfile/ sag@odin:~/express-sendfile $ npm install

  3. instalem "dotenv" : npm install dotenv

  4. posem "PORT=2415" al fitxer ".env"

  5. corregim "/home/sag/express-sendfile/node_modules/dotenv/lib/main.js" per contenir "'use strict';"

  6. engeguem la aplicacio :

    sag@odin:~/express-sendfile $ node server.js

  7. verifiquem que funciona : http://odin:8081/

  8. posem "index.html" sota "./public/" i "photo.css" sota "./public/css/"

  9. dins index.html posem "client.js" amb el codi JavaScript del client

  10. partim index.html en diferents sub-parts i hi posem la hora

  11. des el client agafem control del "click" demanant la foto, rebem la resposta i posem la foto en el lloc adient

  12. els missatges "console.log" del codi del client es poden veure amb Chrome + PF12 !

  13. 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)

  14. versio del node : 5.12

  15. 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"

  16. podem forçar la versio 0.4.0 de python-shell aixi

    $ npm install python-shell@0.4.0 --save

  17. 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

  18. 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.

  19. 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 :

  1. go into the directory containing the project
  2. type git init
  3. create a .gitignore file to indicate all of the files you don’t want to track, as "node_modules"
  4. type git add . to add all of the relevant files
  5. 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

  6. goto github
  7. (github) log in to your account
  8. 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.
  9. click the “Create repository” button - named "Envia_Foto"
  10. (odin) git remote add origin git@github.com:sebastianet/Envia_Foto.git
    or git remote add origin https://github.com/sebastianet/Envia_Foto.git
  11. if there is an error we use "git remote rm origin"
  12. to list the origin we use "git remote -v"
  13. (odin) git push -u origin master - provide usr+pwd to send the code
  14. 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 :


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

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


Amunt! Top Amunt!
Detalls de la ferralla
SC107
SC107 pinout

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
BC547 pinout

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
transistor amb led i ssr

Amb el transistor saturat, passen 16 mA pel SSR i 2 mA pel LED (Rc de 1k5).

Resum de components :

Resum de valors :

specs del SSR CX240D5
SSR CX240D5

Comprem CX240D5 per control de carrega de corrent altern (AC load).

SSR = Solid State Relay

Specs CX240D5 :

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
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 :

7812
7812

Specs 7812 :


BreadBoard Albert
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


Amunt! Top Amunt!
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

Amunt! Top Amunt!
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

  1. install "Simple SMTP" :

    sudo apt-get install ssmtp

    sSMTP, MTA

  2. 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 $

  3. Install mailx :

    sudo apt-get install mailutils (mpack)

  4. 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.

  1. sudo apt-get update {sempre}
  2. sudo apt-get upgrade {delicat}
  3. sudo rpi-update {molt delicat i no oficial - see "apt raspberrypi-firmware"}
  4. sudo apt-get install python-dateutil
  5. sudo apt-get install python-setuptools
  6. sudo apt-get install python-dev
  7. sudo apt-get install libevent-dev
  8. sudo apt-get install ncurses-dev
  9. 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

  10. 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 ?

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)

192.168.0.123:1212 <-> ip-ext:9007 ; acces a la APP Rspi - http://raspall.hopto.org:9007/ 192.168.0.123:22 <-> ip-ext:9008 ; acces putty al Rspi
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
JALL - Vodafone
TC7210

Problemes :

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
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 :

  1. on your Raspberry Pi, boot into the desktop
  2. select Menu > Preferences > Raspberry Pi Configuration > Interfaces
  3. 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 :

  1. navigate to "7 - Advanced Options"
  2. scroll down and select "A0 - Update"
  3. 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

remote desktop at odin

The log lines are :

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 :

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

  1. fem un shell
  2. 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
"deures" o feina que pots fer
(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

  1. 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 !
  2. run command "service miAplicacion start"

Carlos Azaustre (old)

Molt millor així amb systemd :

  1. 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

  2. "/var/www/myapp/app.js" should have "#!/usr/bin/env node" on the very first line
  3. you want the file to be executable: "chmod +x app.js"
  4. copy your service file into the "/etc/systemd/system"
  5. start it with "systemctl start myapp"
  6. make systemd aware of the new service: "sudo systemctl daemon-reload"
  7. enable it to run on boot with "systemctl enable myapp"
  8. 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 :

nice pdf

More specific :

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 :

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

Kubii :

Per peces, a Amason :

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

feina en engegar el R4

Fem servir un servei del tipus "systemd" :

  1. 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

  2. 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

  3. aquest log ha de existir :

    ~$ touch /home/miquel/logs/engegades.log

  4. 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.

  5. el servei s'ha de llistar aixi

    ~$ systemctl --user cat r4_start.service

  6. provem de engegar-lo a veure si no te cap problema (normalment de permisos) :

    ~$ sudo systemctl start r4_start

  7. 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 :


SAG & R4

Specs : url

Us 202102 : Home Assistant

NOOBS, 2020

Lets make it run :

  1. download NOOBS NOOBS_v3_5_1.zip onto MARS & Ubuntu
  2. expand into a directory, lets say "noobs_35"
  3. get rpi-imager

    1. download Raspberry Pi Imager for Ubuntu : imager_1.5_amd64.deb
    2. on Ubuntu, double click on the "*.deb" file to install rpi-imager
  4. format SD as FAT32, using rpi-imager
  5. 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 :

  1. sudo apt update
  2. sudo apt full-upgrade ; url
  3. tenim "Raspbian 10, buster"
Raspbian, 2021

Tenim una micro SDHC "SanDisk Ultra" de 32 GB, clase 10, categoria A1

  1. 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

  2. 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

  3. 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

  4. 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)

  5. 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

  6. 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

  7. 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' ...

  8. make it super-user :

    pi@raspberrypi:/home $ sudo adduser sebas sudo Adding user `sebas' to group `sudo' ... Adding user sebas to group sudo Done.

  9. 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

  10. 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

  11. 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)

  12. 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

  13. 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 :

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

  1. get 2022-01-28-raspios-bullseye-arm64.zip here

  2. expand it to 2022-01-28-raspios-bullseye-armhf.img

  3. {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.

  4. {MARS} Pi imager v1.5 ... writing

  5. 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

  6. botem la nova SD :

    ---[ end Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(172,2) ]---

  7. 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

  8. 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.

  9. **Raspberry Pi 4 Model B:** display must be connected to HDMI port closest to power jack.

  10. boot problems :

    edit /boot/config.txt to include hdmi_force_hotplug=1

    14 solutions, 6 more

  11. 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

  12. 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

  13. 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 -

    1. get 3.3.0 : 07.2020 -> nicolau@mars:~/sebas/rspi/op_sys/2022_3.5/noobs_3.5
    2. format SD using rpi-imager
    3. copy from MARS to SD pointing "INSTRUCTIONS-README.txt" at the root directory of SD card
    4. modificar "/boot/config.txt" per contenir "enable_uart=1"
    5. al MARS, engegar "minicom -b 115200 -D /dev/ttyUSB0"
    6. power-on the R4 : mostra 2 SO's i demana quin instalar -> Raspbian
    7. 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"

  14. 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

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'

Amunt! Top Amunt!
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


Amunt! Top Amunt!
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 :

  1. arrancar la Raspberry Pi desde la micro SD de manera normal
  2. actualizar el sistema operativo : "sudo apt update" + "sudo apt full-upgrade"
  3. "sudo nano /etc/default/rpi-eeprom-update" : cambia el valor «critical» de "RELEASE_STATUS" por «beta» y pulsa CTRL + X para salir y guardar
  4. instalar el bootloader beta : "sudo rpi-eeprom-update -d -f /lib/firmware/raspberrypi/bootloader/beta/pieeprom-2020-05-15.bin"
  5. reboot y verificar version del bootloader con "vcgencmd bootloader_version"
  6. crear SSD o pen drive USB con Raspbian (se puede usar "SD Copier")

hardzone


Amunt! Top Amunt!
Moving to a bigger SD
Raspberry PI tricks: migrating to larger SD card with Windows

  1. required software : windows : Win32DiskImager
  2. insert "small" SD
  3. create "my_sd.img"
  4. insert "big" SD
  5. write IMG on it
  6. boot "big" SD
  7. sudo raspi-config
  8. 7 - Advanced Options
  9. A1 - Expand Filesystem

peppe8o

See canvi SD [***]


Amunt! Top Amunt!
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 = 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

  1. 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
  2. get the package information from the Webmin Debian repository :

    apt update
  3. 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
  4. install webmin : "apt-get install webmin" - some pre-reqs shall fail
  5. "apt --fix-broken install" - install missing dependencies
  6. "apt-get install webmin"
  7. access webmin on Raspbian

varhowto


Amunt! Top Amunt!
Pending


UARTs

There are 6 UARTs on R4, but only 1 of UART0/1 is accessible.

tech info

schematics, BCM 2835 peripherals


Amunt! Top Amunt!
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

cable USB 2 UART
Serial port logging

If you want to access the Pi's serial console, you have to connect the Raspberry UART to a PC :

  1. 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

  2. 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

  3. 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:

    • use minicom with sudo
    • add your user to the dialout group by

      sudo usermod -aG dialout $USER

      Logout and login. After that you'll be able to reach your modem without sudo.

    askubuntu

  4. 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


Amunt! Top Amunt!
Links

Ep ! Valid HTML 4.01!   Valid CSS! Escriu-me !
Updated 20201031 (a)  
Uf !