home / infca / rspi3 (navigation links) Que és lo mes divertit que t'ha passat avui ?
Gracies, JA !

Install | bluetooth | GPIO | Software | Semàfor | SAG : projectes, led, sound, remote control & picture, entrada hw | Alby | wifi | Enviar Email | Enviar WhatsApp | Obrir ports | Lo Pere | ESP, backup, deures | Pi0 | 4 | MTV - deures | Links | End

Jocs amb la Raspberry Pi 3 model B, des l'estiu 2016


Amunt! Top Amunt!
Raspberry 3 model B
Specs

El Raspberry Pi ...

Specs :

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

HDMI on TV

The cable shows up as "v 60 Hz, 1920 x 1080 i"

On-board leds

url

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.4GHz Broadcom BCM2837, Cortex-A53 (ARMv8) 64-bit SoC @ 1.2GHz
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 :

NOOBS setup
  1. download NOOBS into W500 {c:\temp\rsp3\NOOBS_v3_2.zip}
  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: or System Format + "NTFS"
    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 64GB 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ó
  1. NOOBS instala Debian / Raspbian
  2. hostname := "raspall" ;
  3. default user = "pi", default password = "raspberry" ;
  4. passwd pi : u = "pi", p = "b10" ; 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

sebas@henry:~/manuals $ uname -a Linux henry 4.14.79-v7+ #1159 SMP Sun Nov 4 17:50:20 GMT 2018 armv7l GNU/Linux

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 (statis 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

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=80.58.61.250 80.58.61.254

doc

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); 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, used to be 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

tcpdump

  1. sudo apt-cache search tcpdump
  2. sudo apt-get install tcpdump
  3. sudo tcpdump
  4. sudo tcpdump -w test.pcap -c 1000 {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

GPIO 40-pin connector - General Purpose I/O
BCM notation Raspberry 40-pin GPIO connector Raspberry 40-pin GPIO connector

Open a terminal window and run the command pinout (from pinout.xyz - see GPIO, SPI, I2C, GPCLK, UART, ...)

The intensity of 50mA is the total current intensity for all pins simultaneously. The maximum permitted current draw from the 3.3 V pins is 50 mA.

The output drives to either 3.3V (high) or 0V (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.

URL, dibuix

El "Python module to control the GPIO on a Raspberry Pi" mes popular és python rpi gpio - wiki amb exemples.

Ves amb compte amb la numeració dels pins que n'hi ha dues : la BCM i la BOARD.

Per fer-ho anar amb node ens cal rpi-gpio package.

Python : BCM versus BOARD pin notation

When using the RPi.GPIO library in Python you have to call

import RPi.GPIO as GPIO

and then

GPIO.setmode(GPIO.BOARD)

or

GPIO.setmode(GPIO.BCM)

What is the difference ?

Good tutorial

node.js : BCM versus RPI pin notation

Please note that there are two different and confusing ways to reference a channel; either using the Raspberry Pi or the BCM/SoC naming schema.

setMode(mode) - Sets the channel addressing schema.
Mode: Specify either Raspberry Pi or SoC/BCM pin schemas, by passing MODE_RPI or MODE_BCM. Defaults to MODE_RPI.

Pull up / down dels pins del GPIO

Compte ! See document, page 102 and 103.

Pull ...

Display GPIO version

Easy :

sag@odin:~/gpio_python $ sudo python Python 2.7.9 (default, Sep 26 2018, 05:58:52) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import RPi.GPIO as GPIO >>> GPIO.VERSION '0.6.3' >>>

Or code this :

#!/usr/bin/env python import RPi.GPIO as GPIO print "Version GGPIO =", GPIO.VERSION # mostrar la versio de GPIO
How to connect GPIO to a breadboard / protoboard

Per conectar el GPIO del raspberry a una Adle/Board nº 8 cal un cable pla amb un conector per breadboard

Aliexpress "RPi GPIO Breakout Expansion Board + 40pin Flat Ribbon Cable For Raspberry Pi 3 2 Model B & B+" : 2,64 $

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


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

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.

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 */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
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:/etc $ cat rc.local #!/bin/sh -e /usr/bin/odin_restart & exit 0
Events and Scripts

Raspbian uses systemd structure.
What script is lauched at what event ?

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"

To verify it is running, do "ps -ef | grep noip2" {kill it if it is to restart}

To display a trace of its work, do "cat /var/log/syslog | grep noip2"

To force noip2 to update, do "sudo /usr/local/bin/noip2 -c /usr/local/etc/no-ip2.conf"

RASPALL startup : DUC

noip2 + llovetbrossa : raspall.hopto.org

pi@odin:/etc $ cat /usr/bin/raspall_restart {from /etc/rc.local} time_name=`date +"h%H:m%M"` echo "(7) (" $date_name "-" $time_name ") start NOIP2 client to update IP at HOPTO" >> $lfn /usr/local/bin/noip2 -c /usr/local/etc/no-ip2.conf >> $lfn echo "(8) (" $date_name "-" $time_name ") verify NOIP2 client is running" >> $lfn host raspall.hopto.org >> $lfn
ODIN startup : DUC

noip2 + campdefabes : myraspiodin.hopto.org

pi@odin:/etc $ cat /usr/bin/odin_restart {from /etc/rc.local} time_name=`date +"h%H:m%M"` echo "(7) (" $date_name "-" $time_name ") start NOIP2 client to update IP at HOPTO" >> $lfn /usr/local/bin/noip2 -c /usr/local/etc/no-ip2.conf >> $lfn echo "(8) (" $date_name "-" $time_name ") verify NOIP2 client is running" >> $lfn host myraspiodin.hopto.org >> $lfn

SAG's "odin" hw & sw
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/engegades.log . . /usr/bin/node /home/sag/Raspberry-Pi-Simple-Web-GPIO-GUI/bin/www . . /home/sag/express-sendfile/server.js . . . . crontab . . 0 4 * * * /home/pi/eines/cron_feina_send_email.sh -> bisc2k9@gmail.com amb UP interna i externa . . */15 * * * * /home/pi/eines/cron_feina_15_min.sh -> /home/pi/logs/cron_job.log . . /etc/cron.daily ln -s /home/pi/eines/fer_backup.sh enviar_tgz_backup_fitxers . . . . configuration . . noip2 - myraspiodin.hopto.org - /usr/local/etc/no-ip2.conf . . static ip - /etc/dhcpcd.conf . . . . --- /etc/motd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Canvi de 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 rpi i fes un resize amb raspi-config, github
Comandes

$ sudo fdisk -l veure els discs que hi ha a la maquina $ sudo mkdir /mnt/sag fem un punt per muntar la particio $ sudo mount -t auto -v /dev/sda2 /mnt/sag muntem la particio (falta filesystem type) $ sudo umount /mnt/sag desmuntem $ sudo mount -t auto -v /dev/sda3 /mnt/sag muntem la particio bona de windows $ cd /mnt/sag anem a la particio desti de la imatge $ cd TEMP escollim on posar la imatge $ mkdir uSD fem un subdirectori $ cd uSD i ens hi posicionem $ sudo umount /dev/sdb desmuntem el disc "origen" $ sudo dd if=/dev/sdb of=sd.img bs=4M grabem la imatge 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 < posem una SD nova > $ sudo dd if=sd.img of=/dev/sdb bs=4M grabem 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% / $ sudo raspi-config --expand-rootfs url

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

Proves de funcionament del "odin"
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


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.

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)

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
  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 currently)
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(); });

url

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

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 :

    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/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 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); 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 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 GGPIO =", 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") - GPIO27, pin 37 GPIO.setup(ENTRADA, GPIO.IN) # set pin 36 / GPIO16 as input (button) GPIO.setup(SORTIDA, GPIO.OUT) # set pin 37 / GPIO27 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 +++" GPIO.output(SORTIDA, 1) # set port/pin value to 1/HIGH/True else: print "--- pin 36 is 0/LOW/False - led OFF ---" GPIO.output(SORTIDA, 0) # 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 sag@odin:~/gpio_python $

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 :


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,6k.
(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 = 20k

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

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. If you appreciate this software and you would like to support future development please consider donating: http://openwhatsapp.org/yowsup/donate 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); 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 RPI 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 1TB, i a vegades la webcam. Llegir RPI config.

Al raspbian tens "rpi-config" a la shell per tocar aquestes coses mes facil. Llegir Raspbian.

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

url

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"

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

RPI "vcgencmd commands" - usage

pi@raspberrypi-llovet:~/semafor $ vcgencmd measure_temp temp=40.6'C ; temperatura de la GPU
Accés des l'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.

També podem fer servir noip.com

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 (93639.8522.10304), bisk.k9@gmail.com, 83.32.249.161 (20170517)

Volem tenir

192.168.1.123:1212 <-> ip-ext:9009 ; acces a la APP SEMAFOR / RMTC 192.168.1.123:2415 <-> ip-ext:8815 ; acces a la APP Envia Foto http://myraspiodin.hopto.org:8815 192.168.1.123:1313 <-> ip-ext:7171 ; gpio ctrl http://myraspiodin.hopto.org:7171 192.168.1.123:10000 <-> ip-ext:6666 ; administracio remota del Raspberry "Odin" 192.168.1.123:22 <-> ip-ext:9022 ; acces putty/ssh al RSPI - ssh user@myraspiodin.hopto.org -p 9022 {20191016 connection refused} 192.168.1.46:1245 <-> ip-ext:8000 ; proves acces - \\node\web-server-basico at W500
SAG's Alexandra
ESP port forwarding

2424 --- 1144 -- app 3333 --- 22 -- ssh
MTV

9000 --- 22 -- ssh u=sebas p=$+.1
HW router
SAG - Timofonica
JALL - Vodafone
TC7210

Problemes :

pi@raspall:~ $ curl -m 2 -s icanhazip.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 ===========" >> $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 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
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

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) 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
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 -x # 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 # # 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 2.a" myPath="/home/pi/eines" 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/pi/logs/fer_backup.log" szHN=$HOSTNAME fn2Send="pic_"$szHN"_tar.jpg" szDESTI="manel@yandex.com neus@gmx.com" szFiltre="gmx.com" szDeit=$(date +%R) szCOS="+++ $szDeit +++ ($szHN) +++ ($0) +++ ($szVer) +++ Backup files from ($fnIN) sent to ($szDESTI)." echo -e "\n(0) ----------------------------------------------------------------------------------------------------------------------" >> $fnLOG 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 tar -rf $fnOUT $linia >> $fnLOG 2>&1 cnt=$(($cnt+1)) done < $fnIN echo "(3) --- rename de ($fnOUT) a ($fn2Send)" >> $fnLOG mv $fnOUT $fn2Send szSubject="{$szCOS} backup ($cnt) fitxers." echo "(4) --- subject ($szSubject)" >> $fnLOG szBody="* $szDeit * [$szHN] * ($0) sends using mutt *" echo "(5) --- body ($szBody)" >> $fnLOG echo "(6) --- enviem fitxer ($fn2Send) a ($szDESTI)" >> $fnLOG echo "$szBody" | mutt -s "$szSubject" -a "$fn2Send" -- $szDESTI rv=$? echo "$szDeit MAIL return code" $rv >> $fnLOG 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 :

/boot/config.txt /etc/apt/sources.list /etc/Muttrc /etc/motd /etc/rc.local /home/pi/.bash_aliases /home/pi/eines/fer_backup.sh /home/pi/eines/llista_fitxers.txt /usr/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 !

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

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/sebas/eines/python/fer_foto

(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 sudo apt-get upgrade 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 :

More specific :

Kubii : 1 GB = 38 €, 2 GB 49 €.

Use the new Buster, the latest version of Debian Linux

As it has USB 3, we can use a SSD disk !

pi 3 B+ headless SSH access over wifi

Raspberry 4 improvements

Que afegeix el Raspberry 4 ? diferencies :

Raspberry 4 to-buy list

You will need

Kubii :

Per peces, a Amason :

Raspberry 4 MTV

20200503 : amason, 120 €

email at tinet, espai web (sense la "i" ?)

deures per en MTV amb la Raspberry 4


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.

url

Homepage Home Assistant

Picovoice/porcupine

On-device wake word detection powered by deep learning : github


Amunt! Top Amunt!
Pending

Amunt! Top Amunt!
Links

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