網頁

顯示具有 Raspberry 標籤的文章。 顯示所有文章
顯示具有 Raspberry 標籤的文章。 顯示所有文章

2020年8月31日 星期一

在桌面顯示 主機資訊

參考 Ubuntu 20.04 System Monitoring with Conky widgets, Ubuntu 18.04也可用
$ sudo apt-get install conky-all
開始/Startup Applications
加入 /usr/bin/conky
$ sudo reboot
$ cp /etc/conky/conky.conf ~/.conkyrc
$ vi ~/.conkyrc
conky.config = {
update_interval = 1,
cpu_avg_samples = 2,
net_avg_samples = 2,
out_to_console = false,
override_utf8_locale = true,
double_buffer = true,
no_buffers = true,
text_buffer_size = 32768,
imlib_cache_size = 0,
own_window = true,
own_window_type = 'normal',
own_window_argb_visual = true,
own_window_argb_value = 80,
own_window_hints = 'undecorated,below,sticky,skip_taskbar,skip_pager',
border_inner_margin = 5,
border_outer_margin = 0,
xinerama_head = 1,
alignment = 'bottom_right',
gap_x = 0,
gap_y = 33,
draw_shades = false,
draw_outline = false,
draw_borders = false,
draw_graph_borders = false,
use_xft = true,
font = 'Ubuntu Mono:size=12',
xftalpha = 0.8,
uppercase = false,
default_color = 'white',
own_window_colour = '#000000',
minimum_width = 300, minimum_height = 0,
alignment = 'top_right',

};
conky.text = [[
${font sans-serif:bold:size=16}${time %Y-%m-%d}${alignr}${time %H:%M:%S}${font}
${font sans-serif:bold:size=10}SYSTEM ${hr 2}
${font sans-serif:normal:size=8}$sysname $kernel $alignr $machine
Host:$alignr$nodename
Uptime:$alignr$uptime
File System: $alignr${fs_type}
Processes: $alignr ${execi 1000 ps aux | wc -l}

${font sans-serif:bold:size=10}CPU ${hr 2}
${font sans-serif:normal:size=8}${execi 1000 grep model /proc/cpuinfo | cut -d : -f2 | tail -1 | sed 's/\s//'}
${font sans-serif:normal:size=8}CPU:${cpugraph cpu0 50}
CPU: ${cpu cpu0}% ${cpubar cpu0}

${font sans-serif:bold:size=10}Nvidia GPU ${hr 2}
${font sans-serif:normal:size=8}${execpi 1000 (nvidia-smi --query-gpu=gpu_name --format=csv,noheader)}
Temperature:${alignr}${execpi 3 (nvidia-smi --query-gpu=temperature.gpu --format=csv,noheader)}°C
Fan Speed:${alignr}${execpi 3 (nvidia-smi --query-gpu=fan.speed --format=csv,noheader)}
Utilization:${alignr}${execpi 3 (nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader)}
Power:${alignr}${execpi 3 (nvidia-smi --query-gpu=power.draw --format=csv,noheader,nounits)}/${execpi 10 (nvidia-smi --query-gpu=power.default_limit --format=csv,noheader)}
Memory:${alignr}${execpi 3 (nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits)}/${execpi 10 (nvidia-smi --query-gpu=memory.total --format=csv,noheader)}
${font Courier-New:normal:size=8}PID${alignc}Name${alignr}Memory
${execpi 3 (nvidia-smi -q|tr -d " "|awk -F ":" '/ProcessID/{printf $2"\t";getline;getline;printf "%-28s",substr($2, 1, 28)"\t";getline;printf $2"\n"}')}

${font sans-serif:bold:size=10}MEMORY ${hr 2}
${font sans-serif:normal:size=8}RAM $alignc $mem / $memmax $alignr $memperc%
$membar
SWAP $alignc ${swap} / ${swapmax} $alignr ${swapperc}%
${swapbar}

${font sans-serif:bold:size=10}DISK USAGE ${hr 2}
${font sans-serif:normal:size=8}/ $alignc ${fs_used /} / ${fs_size /} $alignr ${fs_used_perc /}%
${fs_bar /}

${font Ubuntu:bold:size=10}NETWORK ${hr 2}
${font sans-serif:normal:size=8}Local IPs:${alignr}External IP:
${execi 1000 ip a | grep inet | grep -vw lo | grep -v inet6 | cut -d \/ -f1 | sed 's/[^0-9\.]*//g'}  ${alignr}${execi 1000  wget -q -O- http://ipecho.net/plain; echo}
${font sans-serif:normal:size=8}Down: ${downspeed eno1}  ${alignr}Up: ${upspeed eno1} 
${color lightgray}${downspeedgraph eno1 80,130 } ${alignr}${upspeedgraph eno1 80,130 }$color
${font sans-serif:bold:size=10}TOP PROCESSES ${hr 2}
${font sans-serif:normal:size=8}Name $alignr PID   CPU%   MEM%${font sans-serif:normal:size=8}
${top name 1} $alignr ${top pid 1} ${top cpu 1}% ${top mem 1}%
${top name 2} $alignr ${top pid 2} ${top cpu 2}% ${top mem 2}%
${top name 3} $alignr ${top pid 3} ${top cpu 3}% ${top mem 3}%
${top name 4} $alignr ${top pid 4} ${top cpu 4}% ${top mem 4}%
${top name 5} $alignr ${top pid 5} ${top cpu 5}% ${top mem 5}%
${top name 6} $alignr ${top pid 6} ${top cpu 6}% ${top mem 6}%
${top name 7} $alignr ${top pid 7} ${top cpu 7}% ${top mem 7}%
${top name 8} $alignr ${top pid 8} ${top cpu 8}% ${top mem 8}%
${top name 9} $alignr ${top pid 9} ${top cpu 9}% ${top mem 9}%
${top name 10} $alignr ${top pid 10} ${top cpu 10}% ${top mem 10}%
]];


其中花費最多時間的是
nvidia-smi -q|tr -d " "|awk -F ":" '/ProcessID/{printf $2"\t";getline;getline;printf "%-28s",substr($2, 1, 28)"\t";getline;printf $2"\n"}'
增加 Nvidia GPU 資料

2020年6月10日 星期三

Bluetooth tools bluetoothctl

nano@nano-desktop:~$ bluetoothctl
[NEW] Controller 5C:87:9C:1D:A8:7F nano-desktop [default]
[NEW] Device 00:1C:BE:B7:E0:9D Nintendo RVL-WBC-01
[NEW] Device EA:40:D8:89:24:66 BBC micro:bit
[NEW] Device 30:23:63:70:8E:22 E-books E-EPA173
[NEW] Device C4:4F:33:54:B5:3B ESP32
[NEW] Primary Service
        /org/bluez/hci0/dev_C4_4F_33_54_B5_3B/service0028
        4fafc201-1fb5-459e-8fcc-c5c9c331914b
        Vendor specific
[NEW] Characteristic
        /org/bluez/hci0/dev_C4_4F_33_54_B5_3B/service0028/char0029
        beb5483e-36e1-4688-b7f5-ea07361b26a8
        Vendor specific

2020年5月28日 星期四

Joystick of MicroBit and Raspberry PI, Part 2

MicroBit 之 JavaScript
bluetooth.onUartDataReceived(serial.delimiters(Delimiters.Hash), function () {
    basic.showString(bluetooth.uartReadUntil(serial.delimiters(Delimiters.Hash)))
})
bluetooth.onBluetoothDisconnected(function () {
    bCnt = 0
    basic.showLeds(`
        # . . . #
        . # . # .
        . . # . .
        . # . # .
        # . . . #
        `)
})
bluetooth.onBluetoothConnected(function () {
    bCnt = 1
    basic.showLeds(`
        . . . . .
        . . . . #
        . . . # .
        # . # . .
        . # . . .
        `)
})
let bCnt = 0
bCnt = 0
pins.setPull(DigitalPin.P5, PinPullMode.PullUp)
pins.setPull(DigitalPin.P11, PinPullMode.PullUp)
pins.setPull(DigitalPin.P15, PinPullMode.PullUp)
pins.setPull(DigitalPin.P14, PinPullMode.PullUp)
pins.setPull(DigitalPin.P13, PinPullMode.PullUp)
pins.setPull(DigitalPin.P12, PinPullMode.PullUp)
bluetooth.startUartService()
basic.showString("b")
basic.forever(function () {
    if (bCnt == 1) {
        bluetooth.uartWriteString("A" + pins.digitalReadPin(DigitalPin.P5) + pins.digitalReadPin(DigitalPin.P11) + pins.digitalReadPin(DigitalPin.P15) + pins.digitalReadPin(DigitalPin.P14) + pins.digitalReadPin(DigitalPin.P13) + pins.digitalReadPin(DigitalPin.P12) + "B" + pins.digitalReadPin(DigitalPin.P8) + "C" + pins.analogReadPin(AnalogPin.P1) + "D" + pins.analogReadPin(AnalogPin.P2))
        bluetooth.uartWriteString("E" + input.acceleration(Dimension.X) + "F" + input.acceleration(Dimension.Y) + "G" + input.acceleration(Dimension.Z) + "H" + input.acceleration(Dimension.Strength) + "I" + input.temperature())
    }
    basic.pause(1)
})

樹莓派上的 python
from bluezero import microbit
from bluezero import async_tools

def uart_callback(rt):
    #print(rt)
    pass
    
def ping():
    ubit.uart = 'ping#'
    return True

def goodbye():
    ubit.quit_async()
    ubit.disconnect()
    return False

ubit = microbit.Microbit(adapter_addr='DC:A6:32:9D:C9:74',
    device_addr='EA:40:D8:89:24:66', # tipet
    #device_addr='FF:06:9C:77:46:E9', # gaviv
    accelerometer_service=False,
    button_service=False,
    led_service=False,
    magnetometer_service=False,
    pin_service=False,
    temperature_service=False,
    uart_service=True)
eloop = async_tools.EventLoop()

ubit.connect()

ubit.subscribe_uart(uart_callback)
eloop.add_timer(10000, ping)
eloop.add_timer(30000, goodbye)

ubit.run_async()


Joystick of MicroBit and Raspberry PI

將 MicroBit 的搖桿透過藍芽連上樹莓派
參考 Waveshare 之 Joystick

到 https://makecode.microbit.org/ 編寫程式 切換 JavaScript 可以直接貼上
bluetooth.onBluetoothConnected(function () {
    basic.showString("C")
})
bluetooth.onBluetoothDisconnected(function () {
    basic.showString("D")
})
pins.setPull(DigitalPin.P5, PinPullMode.PullUp)
pins.setPull(DigitalPin.P11, PinPullMode.PullUp)
pins.setPull(DigitalPin.P15, PinPullMode.PullUp)
pins.setPull(DigitalPin.P14, PinPullMode.PullUp)
pins.setPull(DigitalPin.P13, PinPullMode.PullUp)
pins.setPull(DigitalPin.P12, PinPullMode.PullUp)
basic.showLeds(`
    # . . # #
    # . . # #
    # # # . .
    # . # . .
    # # # . .
    `)
bluetooth.startAccelerometerService()
bluetooth.startLEDService()
bluetooth.startIOPinService()
bluetooth.startTemperatureService()

右上齒輪/Project Settings
選擇 JustWorks pairing(default): Pairing is automatic once the pairing is initiated.
下載至 MicroBit

同時按下 AB 兩按鈕,再按下背面的 Reset 並放開 Reset
等待 畫面顯示完成,放開 AB 兩按鈕
在樹莓派右下角藍芽圖示,按滑鼠右鍵
選擇 Add Device
選擇 MicroBit, 按 Pair

參考 https://github.com/jaglees/pibit
參考 python-bluezero
參考 https://github.com/ukBaz/python-bluezero

$ bluetoothctl
[bluetooth]# show
Controller 5C:87:9C:1D:A8:7F (public)
Name: nano-desktop
Alias: nano-desktop
Class: 0x00000000
Powered: yes
Discoverable: no
Pairable: yes
UUID: Generic Attribute Profile (00001801-0000-1000-8000-00805f9b34fb)
UUID: PnP Information           (00001200-0000-1000-8000-00805f9b34fb)
UUID: Generic Access Profile    (00001800-0000-1000-8000-00805f9b34fb)
Modalias: usb:v1D6Bp0246d0530
Discovering: no
取得 adapter 的 MAC Address
[bluetooth]# power off
[bluetooth]# agent off
[bluetooth]# scan off
[bluetooth]# power on
[bluetooth]# agent on
[bluetooth]# scan on
取得 MicroBit 的 MAC Address
[bluetooth]# connect EA:40:D8:89:24:66
[bluetooth]# pair EA:40:D8:89:24:66
若是一直不成功,試試 remove, 再去 connect
[bluetooth]# remove EA:40:D8:89:24:66


將 MicroBit 的 MAC Address 填入 microbits.cnf
修改 python 程式中的 adapter

import time
from bluezero import microbit
from keyboardRead import NonBlockingConsole

# Set the address of the Pi Bluetooth controler
adapter='DC:A6:32:9D:C9:74'

devices={}
filepath = './microbits.cnf'
print ("Initialising microbits found in ", filepath)
try: 

    # Read list of Microbit MAC addresses and attempt to connect to each
    with open(filepath) as fp:
        line = fp.readline()
        while line:
            key=line.strip()
            print ("..Device: [",key.strip(),"]")
            try:
                # Define microbit object
                print ("....Initialising")
                devices[key] = microbit.Microbit(adapter_addr=adapter,
                                    device_addr=key,
                                    accelerometer_service=True,
                                    button_service=False,
                                    led_service=True,
                                    magnetometer_service=False,
                                    pin_service=True,
                                    temperature_service=True)
                print ("....Initialised")

                # Connect to microbit
                print ("....Connecting")
                devices[key].connect()
                print ("....Connected")
                devices[key].set_pin(5, True, False)
                devices[key].set_pin(11, True, False)
                devices[key].set_pin(15, True, False)
                devices[key].set_pin(14, True, False)
                devices[key].set_pin(13, True, False)
                devices[key].set_pin(12, True, False)
                devices[key].set_pin(1, True, True)
                devices[key].set_pin(2, True, True)
                devices[key].set_pin(8, True, False)
            except Exception as e:
                # If initilisation or connection failed remove this device from device list
                print(e)
                print ("....Initialisation or Connection failed")
                devices.pop(key, None)

            line=fp.readline()
except:
    print("Failed to open config file")
    exit()

# Check that at least one device is connected to - if not exit
if (devices is None or len(devices)==0):
    print ("No connected devices - exiting")
    exit()

# Loop whilst listening for keyboard input (on the Pi)
with NonBlockingConsole() as nbc:
    looping = True
    while looping:

        # Check each device in turn - getting the unique key of each device
        for dKey in devices:
            
            # If the escape key is pressed on the PI then break
            keyboardVal = nbc.get_data()
            if keyboardVal == '\x1b':  # x1b is ESC
                print ("Raspberry Pi Escape key pressed")
                looping=False
            elif keyboardVal == 'm':  
                msg = input("Enter message to output to all Pis:")
                for d in devices:
                    devices[d].text=msg


            # If the A button is pressed - exit the loop (a kill switch)
            #if (devices[dKey].button_a > 0):
            #    print("Device [", dKey, "] Button A Pressed" )
            #    #looping=False
            
            # Print the temperature from the device 
            print('Temperature [', dKey, '] = ', devices[dKey].temperature)
            print('Accelerometer [', dKey, '] = ', devices[dKey].accelerometer)
            #print("Device [", dKey, "] Button A = " , devices[dKey].button_a)
            #print("Device [", dKey, "] Button B = " , devices[dKey].button_b)
            print("Device [", dKey, "] Pin = " , devices[dKey].pin_values)
        
        time.sleep(1)


# Tidy up by disconnecting from all devices
print ("Disconnecting from all devices")
for dKey in devices:
    print ("..Device [",dKey,"]")
    print ("....Disconnecting")
    devices[key].disconnect()
    print ("....Disconnected")

2020年5月27日 星期三

Connect Raspberry PI and Wii

以下以適用 Jetson Nano

搖桿, Gamepad, Joysticks
參考 Wiimote Controller Configuration for Raspberry Pi 2/3
參考 How to Connect Wiimotes to the Raspberry Pi
參考 wminput.list
參考 action_enum.txt
參考 pd-l2ork cwiid

$ cat mywminput
# Classic-Controller
#Classic.Dpad.X = ABS_X
#Classic.Dpad.Y = ABS_Y
#Classic.LStick.X = ABS_HAT0X
#Classic.LStick.Y = ABS_HAT0Y
#Classic.RStick.X = ABS_HAT1X
#Classic.RStick.Y = ABS_HAT1Y
Classic.A = BTN_A
Classic.B = BTN_B
Classic.X = BTN_X
Classic.Y = BTN_Y
Classic.Minus = BTN_SELECT
Classic.Plus  = BTN_START
Classic.Home  = BTN_MODE
Classic.L  = BTN_TL
Classic.R  = BTN_TR
Classic.ZL = BTN_TL2
Classic.ZR = BTN_TR2

# WiiMote
Wiimote.A = BTN_A
Wiimote.B  = BTN_B
Wiimote.Dpad.X = ABS_HAT0X
Wiimote.Dpad.Y = -ABS_HAT0Y
Wiimote.Minus = BTN_SELECT
Wiimote.Plus = BTN_START
Wiimote.Home = BTN_MODE
Wiimote.1 = BTN_X
Wiimote.2 = BTN_Y

# Nunchuk
Nunchuk.C = BTN_C
Nunchuk.Z = BTN_Z
Nunchuk.Stick.X = ABS_RX
Nunchuk.Stick.Y = -ABS_RY

Plugin.led.Led1 = 1
#Plugin.led.Led2 = 1
#Plugin.led.Led3 = 1
#Plugin.led.Led4 = 1

Plugin.ir_ptr.X = ABS_HAT1X
Plugin.ir_ptr.Y = ABS_HAT1Y

Plugin.acc.X = ABS_X
Plugin.acc.Y = ABS_Y
#Plugin.acc.Z = ABS_Z


$ cat connectwii.sh

#!/bin/bash
sleep 1 # Wait until Bluetooth services are fully initialized
hcitool dev | grep hci >/dev/null
if test $? -eq 0 ; then
    wminput -d -c  /home/pi/mywminput 00:1A:E9:EB:07:2A &
else
    echo "Blue-tooth adapter not present!"
    exit 1
fi

同時按下1,2 並放開
$ sudo ./connectwiimote.sh
$ sudo apt-get install jstest-gtk
$ jstest-gtk
$ ps -efa | grep wminput
$ sudo kill -9 pid


使用 python 控制
參考 Raspberry Pi 4 bluetooth scale
參考 wiiweigh
參考 xwiimote

export PYTHONPATH=/usr/lib/python2.7/site-packages
sudo visudo
Defaults env_keep += "PYTHONPATH"
加入上一行

同時按下1,2 並放開
$ bluetoothctl
[bluetooth]# connect 00:1A:E9:EB:07:2A
[bluetooth]# exit
$ xwiishow list
Listing connected Wii Remote devices:
  Found device #1: /sys/devices/platform/soc/fe201000.serial/tty/ttyAMA0/hci0/hci0:12/0005:057E:0306.0004
End of device list
$ xwiishow 1
$ bluetoothctl
[bluetooth]# disconnect 00:1A:E9:EB:07:2A
[bluetooth]# exit
$ cd src/xwiimote-bindings/examples/python
$ sudo python xwiimote_test.py

可以加入下列程式
        elif evt.type == xwiimote.EVENT_NUNCHUK_KEY:
            code, state = evt.get_key()
            print "Nunchuk Key:", code, ", State:", state
        elif evt.type == xwiimote.EVENT_NUNCHUK_MOVE:
            x, y, z = evt.get_abs(0)
            #print "Nunchuk controller move 1:", x, y
        elif evt.type == xwiimote.EVENT_ACCEL:
            x, y, z = evt.get_abs(0)
            #print "Accelerometer move 1:", x, y, z


Wii Balance Board
參考 chaosbiber / wiiweigh
參考 Raspberry Pi Smart Scale
參考 Disassembling Wii Balance Board
參考 Wii Balance Board Smart Scale ( w/ ESP32 )

HX711接腳
青-E+
綠-E-
紅-A-
白-A+

雙黑 開關
LED 白P 青N

2020年5月18日 星期一

測試 SD Card 速度

釋放Linux記憶體
# echo 1 > /proc/sys/vm/drop_caches
釋放dentries、inodes所用的 cache memory。
# echo 2 > /proc/sys/vm/drop_caches
釋放pagecache、dentry、inode 所用的 cache memory。
# echo 3 > /proc/sys/vm/drop_caches
完全釋放cache memory,必須先執行sync,避免錯誤。
# sync

Write speed
# sync; time dd if=/dev/zero of=~/test.tmp bs=500K count=1024
Read speed
# sync; echo 3 | sudo tee /proc/sys/vm/drop_caches
# sync; time dd if=~/test.tmp of=/dev/null bs=500K count=1024

SanDisk microSDHC 32GB Extreme U3 90MB/s
Arduino 寫速度測試
root@arduino:/mnt/sda1# sync; time dd if=/dev/zero of=test.tmp bs=500K count=1024
1024+0 records in
1024+0 records out
real    2m 25.16s
user    0m 0.04s
sys     0m 20.11s
Arduino 讀速度測試
root@arduino:/mnt/sda1# sync; echo 3|tee /proc/sys/vm/drop_caches
3
root@arduino:/mnt/sda1# sync; time dd if=test.tmp of=/dev/null bs=500k count=1024
1024+0 records in
1024+0 records out
real    0m 30.68s
user    0m 0.00s
sys     0m 8.86s
root@arduino:/mnt/sda1# uname -a
Linux arduino 3.3.8 #1 Thu Jun 2 12:28:33 CEST 2016 mips GNU/Linux
root@arduino:/mnt/sda1#
Arduino 拍照測試(不下載)
root@arduino:/# time gphoto2 --port usb:001,003 --capture-image
New file is in location /capt0000.jpg on the camera
real    0m 4.92s
user    0m 1.74s
sys     0m 0.36s
Arduino 拍照測試,下載到 Flash
root@arduino:/# time gphoto2 --port usb:001,003 --capture-image-and-download --no-keep
New file is in location /capt0000.jpg on the camera
Saving file as capt0000.jpg
Deleting file /capt0000.jpg on the camera
Deleting 'capt0000.jpg' from folder '/'...
real    0m 22.88s
user    0m 1.23s
sys     0m 8.77s
root@arduino:/#
Arduino 拍照測試,下載到 SD Card
root@arduino:/mnt/sda1# time gphoto2 --port usb:001,003 --capture-image-and-down
load --no-keep
New file is in location /capt0000.jpg on the camera
Saving file as capt0000.jpg
Deleting file /capt0000.jpg on the camera
Deleting 'capt0000.jpg' from folder '/'...
real    0m 6.53s
user    0m 1.81s
sys     0m 0.58s
root@arduino:/mnt/sda1#
RaspberryPi 寫速度測試
pi@raspberrypi:~ $ sync; echo 3| sudo tee /proc/sys/vm/drop_caches
3
pi@raspberrypi:~ $ sync; time dd if=/dev/zero of=test.tmp bs=500k count=1024
1024+0 records in
1024+0 records out
524288000 bytes (524 MB) copied, 27.8328 s, 18.8 MB/s

real 0m27.847s
user 0m0.020s
sys 0m3.360s
RaspberryPi 讀速度測試
pi@raspberrypi:~ $ sync; echo 3| sudo tee /proc/sys/vm/drop_caches
3
pi@raspberrypi:~ $ sync; time dd if=test.tmp of=/dev/null bs=500k count=1024
1024+0 records in
1024+0 records out
524288000 bytes (524 MB) copied, 22.8695 s, 22.9 MB/s

real 0m22.877s
user 0m0.050s
sys 0m1.340s
pi@raspberrypi:~ $ 
RaspberryPi 拍照測試(不下載)
pi@raspberrypi:~ $ time gphoto2 --port usb:001,004 --capture-image
New file is in location /capt0000.jpg on the camera                            

real 0m3.011s
user 0m0.150s
sys 0m0.100s
RaspberryPi 拍照測試(下載)
pi@raspberrypi:~ $ time gphoto2 --port usb:001,004 --capture-image-and-download --no-keep
New file is in location /capt0000.jpg on the camera                            
Saving file as capt0000.jpg
Deleting file /capt0000.jpg on the camera
Deleting 'capt0000.jpg' from folder '/'...

real 0m3.037s
user 0m0.140s
sys 0m0.140s
pi@raspberrypi:~ $ 


SanDisk ExtremePRO microSDHC UHS-I(V30) 32GB
Arduino 寫速度測試
root@arduino:/mnt/sda1# sync; time dd if=/dev/zero of=test.tmp bs=500K count=1024
1024+0 records in
1024+0 records out
real    2m 32.46s
user    0m 0.01s
sys     0m 20.18s
Arduino 讀速度測試
root@arduino:/mnt/sda1# sync; echo 3|tee /proc/sys/vm/drop_caches
3
root@arduino:/mnt/sda1# sync; time dd if=test.tmp of=/dev/null bs=500k count=1024
1024+0 records in
1024+0 records out
real    0m 30.80s
user    0m 0.00s
sys     0m 8.52s
root@arduino:/mnt/sda1#
Arduino 拍照測試(不下載)
root@arduino:/# time gphoto2 --port usb:001,003 --capture-image
New file is in location /capt0000.jpg on the camera
real    0m 4.92s
user    0m 1.74s
sys     0m 0.45s
Arduino 拍照測試,下載到 Flash
root@arduino:/# time gphoto2 --port usb:001,003 --capture-image-and-download --no-keep
New file is in location /capt0000.jpg on the camera
Saving file as capt0000.jpg
Deleting file /capt0000.jpg on the camera
Deleting 'capt0000.jpg' from folder '/'...
real    0m 22.96s
user    0m 1.19s
sys     0m 9.09s
root@arduino:/#
Arduino 拍照測試,下載到 SD Card
root@arduino:/mnt/sda1# time gphoto2 --port usb:001,003 --capture-image-and-download --no-keep
New file is in location /capt0000.jpg on the camera
Saving file as capt0000.jpg
Deleting file /capt0000.jpg on the camera
Deleting 'capt0000.jpg' from folder '/'...
real    0m 5.89s
user    0m 1.80s
sys     0m 0.45s
root@arduino:/mnt/sda1#


RaspberryPi 寫速度測試
pi@raspberrypi:~ $ sync; echo 3| sudo tee /proc/sys/vm/drop_caches
3
pi@raspberrypi:~ $ sync; time dd if=/dev/zero of=test.tmp bs=500k count=1024
1024+0 records in
1024+0 records out
524288000 bytes (524 MB) copied, 27.6452 s, 19.0 MB/s

real 0m27.657s
user 0m0.000s
sys 0m4.020s
RaspberryPi 讀速度測試
pi@raspberrypi:~ $ sync; echo 3| sudo tee /proc/sys/vm/drop_caches
3
pi@raspberrypi:~ $ sync; time dd if=test.tmp of=/dev/null bs=500k count=1024
1024+0 records in
1024+0 records out
524288000 bytes (524 MB) copied, 23.0098 s, 22.8 MB/s

real 0m23.020s
user 0m0.000s
sys 0m1.610s
pi@raspberrypi:~ $ 
RaspberryPi 拍照測試(不下載)
pi@raspberrypi:~ $ time gphoto2 --port usb:001,004 --capture-image
New file is in location /capt0000.jpg on the camera                          

real 0m3.053s
user 0m0.160s
sys 0m0.140s
RaspberryPi 拍照測試(下載)
pi@raspberrypi:~ $ time gphoto2 --port usb:001,004 --capture-image-and-download --no-keep
New file is in location /capt0000.jpg on the camera                          
Saving file as capt0000.jpg
Deleting file /capt0000.jpg on the camera
Deleting 'capt0000.jpg' from folder '/'...

real 0m2.994s
user 0m0.170s
sys 0m0.070s
pi@raspberrypi:~ $ 

2020年5月15日 星期五

Raspberry Pi 4 安裝

不要使用 NOBBS,直接下載 Raw Images 安裝
https://downloads.raspberrypi.org/raspbian_latest
下載 SD 卡寫入工具
http://sourceforge.net/projects/win32diskimager/

網路相關
參考 https://www.raspberrypi.com.tw/2152/setting-up-wifi-with-the-command-line/
$ iwconfig wlan0
$ sudo iwlist wlan0 scan
$ sudo ifdown wlan0
$ sudo ifup wlan0
$ sudo kill -9 $(ps -ef |grep wpa | awk '{print $2}')
$ sudo wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf
$sudo dhclient
/etc/dhcpcd.conf
/etc/wpa_supplicant/wap_supplicant.conf

network={
 ssid="foo"
 psk="yourpassword"
 proto=RSN
 key_mgmt=WPA-PSK
 pairwise=CCMP
 auth_alg=OPEN
}

/etc/wpa_supplicant/functions.sh
將 WPA_SUP_OPTIONS="$WPA_SUP_OPTI"ONS -D nl80211,wext
改成 WPA_SUP_OPTIONS="$WPA_SUP_OPTI"ONS -D wext,nl80211

工作列/滑鼠右鍵/Add/Remove Panel Items
選 Panel Applets/按 Add
選 CPU Temperature Monitor/按 Add
工作列出現 CPU 溫度顯示

工作列/時間/滑鼠右鍵/Digital Clock Settings
Clock Format: %Y/%m/%d %H:%M:%S

工具列/聲音/滑鼠右鍵
選擇 Analog | HDMI

1. 更新 /etc/apt/sources.list 底下的套件清單
$ sudo apt-get update
2. 比對套件清單決定是否更新,若有相依性問題則放棄
$ sudo apt-get upgrade
3. 處理新版本套件與相依性套件的衝突,並嘗試安裝/移除有問題的套件
$ sudo apt-get dist-upgrade
4. 刪除因相依性而安裝,但已經不使用的套件
$ sudo apt-get autoremove
5. 清除 /var/cache/apt/archives 的 .deb 套件檔
$ sudo apt-get autoclean
6. 更新核心和韌體到最新版(請備份ˇ)
$ sudo rpi-update

開始/Perferences/Raspberry Pi Configuration
點選 Interfaces
Enable SSH 和 VNC
重新開機
工具列/VNC/滑鼠右鍵/Options
Security/Authentication 選 VNC password
Users&Permissions/選 Standard user/按 Password
輸入 password
按OK
設定沒有接螢幕時的解析度
$ sudo raspi-config
7 Advanced Options
A5 Resolution
選擇預設的解析度
重新開機(會等很久,不要擔心)

$ sudo apt install xscreensaver
開始/Perferences/Screensaver 無法使用,改用下列命令
重新開機
$ xscreensaver-demo
Display Modes/Mode 選 Blank Screen Only

安裝SCIM輸入法
$ sudo apt-get install scim scim-tables-zh
安裝新酷音輸入法
$ sudo apt-get install scim-chewing
開始/Perferences/SCIM Input Method
FontEnd/Global Setup
按 Next input method 右邊的按鈕
按 ... 按鈕
按鍵盤左邊的 Shift
按 +
按 OK
IMEngine/Global Setup
取消簡體字和不需要的輸入法
按右下角的 箭頭按鈕
按 OK
開始/Perferences/Raspberry Pi Configuration
Localisation/Set Locale
Language: zh
Country: TW
Character Set: UTF-8
按 OK
重新開機

安裝 chromium 80
下載 https://packages.debian.org/buster/armhf/chromium/download
$ sudo apt remove chromium-browser
$ sudo apt install libminizip1 libre2-5 chromium-common
$ sudo apt install libjsoncpp1
$ sudo dpkg -i chromium_80.0.3987.149-1_deb10u1_armhf.deb
設定 chromium 的 title bar
Chrome menu/Settings
Appearance 取消勾選 Use system title bar and borders

更改滑鼠捲動方向
參考 How to invert mouse scroll in Raspbian?
$ xinput list
Virtual core pointer                    id=2 [master pointer  (3)]
  Virtual core XTEST pointer              id=4 [slave  pointer  (2)]
  Logitech K400                            id=6 [slave  pointer  (2)]
Virtual core keyboard                    id=3 [master keyboard (2)]
  Virtual core XTEST keyboard              id=5 [slave  keyboard (3)]
  Logitech K400                            id=7 [slave  keyboard (3)]
$ xinput list-props 6
$ xinput set-prop 6 "libinput Natural Scrolling Enabled" 1

2017年9月5日 星期二

SSL, RaspberryPi Server, Android Client

請參考 Android 與 Raspberry 證書 和 SSL 網路程式設計 的 Server 端
在此提供 Android 的 Client

package com.example.mark.sslclient;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/** * Created by mark on 2017/9/1. */
public class SSLClient {
    static SSLContext ssl_ctx;

    public SSLClient(Context context) {
        try {
            Log.d("SSLClient", "SSLClient");

            //  Setup truststore            KeyStore trustStore = KeyStore.getInstance("BKS");
            InputStream trustStoreStream = context.getResources().openRawResource(R.raw.android);
            trustStore.load(trustStoreStream, "store1234".toCharArray());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            Log.d("SSLClient", "Trust " + trustStore.size());
            Log.d("SSLClient", "trustManagerFactory " + trustManagerFactory.getTrustManagers().length);

            //  Setup keystore            KeyStore keyStore = KeyStore.getInstance("BKS");
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            InputStream keyStoreStream = context.getResources().openRawResource(R.raw.android);
            keyStore.load(keyStoreStream, "store1234".toCharArray());
            keyManagerFactory.init(keyStore, "key1234".toCharArray());
            Log.d("SSLClient", "Key " + keyStore.size());
            Log.d("SSLClient", "keyManagerFactory " + keyManagerFactory.getKeyManagers().length);

            // Setup the SSL context to use the truststore and keystore            ssl_ctx = SSLContext.getInstance("TLS");
            if (true) {
                ssl_ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            } else {
                TrustManager tm = new X509TrustManager() {
                    public void checkClientTrusted(X509Certificate[] chain, String authTyhpe) throws CertificateException {
                    }
                    public void checkServerTrusted(X509Certificate[] chain, String authTyhpe) throws CertificateException {
                    }
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                };
                ssl_ctx.init(null, new TrustManager[] { tm }, null);
            }
        } catch (KeyStoreException e) {
            Log.d("SSLClient", e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            Log.d("SSLClient", e.getMessage());
        } catch (CertificateException e) {
            Log.d("SSLClient", e.getMessage());
        } catch (IOException e) {
            Log.d("SSLClient", e.getMessage());
        } catch (KeyManagementException e) {
            Log.d("SSLClient", e.getMessage());
        } catch (UnrecoverableKeyException e) {
            Log.d("SSLClient", e.getMessage());
        }
    }
}

package com.example.mark.sslclient;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private SSLClient sslClient;

    private Runnable threadMain = new Runnable() {
        @Override        public void run() {
            SSLSocketFactory socketFactory = (SSLSocketFactory)sslClient.ssl_ctx.getSocketFactory();
            try {
                Log.d(TAG, "threadMain createSocket a");
                SSLSocket socket = (SSLSocket)socketFactory.createSocket("192.168.1.61", 8080);
                Log.d(TAG, "threadMain createSocket b");
                PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
                BufferedReader input = new BufferedReader((new InputStreamReader(socket.getInputStream())));
                output.println("\nthis is from client+++++++++++++++client send to server");
                output.flush();
                Log.d(TAG, "threadMain input.readLine() a");
                String line = input.readLine();
                while (line != null) {
                    Log.d(TAG, line);
                    line = input.readLine();
                }
                Log.d(TAG, "threadMain input.readLine() b");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate a");
        setContentView(R.layout.activity_main);

        sslClient = new SSLClient(this);
        Thread thread = new Thread(threadMain);
        thread.start();
        Log.d(TAG, "onCreate b");
    }
}

2017年9月4日 星期一

Android 與 Raspberry 證書

請參考先前的 Raspberry OPENSSL 根證書 伺服端 客戶端
和 Java keytool and Android

// 產生 Android 要用的 key 和 keystore
D:\SVN_Repository3\pi\Key>"C:\Program Files\Java\jdk1.7.0_67\bin\keytool.exe" -validity 3650 -genkey -v -alias android -keyalg RSA -keystore android.jks -dname "CN=AndroidClient,OU=R&D,O=SDL,L=Taichung,ST=Taiwan,c=TW" -storepass store1234 -keypass key1234
針對 CN=AndroidClient, OU=R&D, O=SDL, L=Taichung, ST=Taiwan, C=TW 產生有效期 3,650 天的 2,048 位元 RSA 金鑰組以及自我簽署憑證 (SHA256withRSA)

[儲存 android.jks]

D:\SVN_Repository3\pi\Key>
// 產生申請證書
D:\SVN_Repository3\pi\Key>"C:\Program Files\Java\jdk1.7.0_67\bin\keytool.exe" -certreq -keystore android.jks -alias android -file android.csr -storepass store1234 -keypass key1234

D:\SVN_Repository3\pi\Key>dir
 磁碟區 D 中的磁碟是 新增磁碟區
 磁碟區序號:  3AAA-91FF

 D:\SVN_Repository3\pi\Key 的目錄

2017/09/04  11:15    <DIR>          .
2017/09/04  11:15    <DIR>          ..
2017/09/04  11:15             1,086 android.csr
2017/09/04  11:14             2,231 android.jks
               2 個檔案           3,317 位元組
               2 個目錄  678,150,483,968 位元組可用

D:\SVN_Repository3\pi\Key>

// 傳送 android.csr 到 RaspberryPi, 並簽署
pi@raspberrypi:~/OpenSSL/openssl $ openssl ca -in android/android.csr -out android/android.crt -days 3650 -cert ca/ca.crt -keyfile ca/ca.key -config openssl.cnf

Using configuration from openssl.cnf
Check that the request matches the signature
Signature ok
The stateOrProvinceName field needed to be the same in the
CA certificate (Taiwan) and the request (Taiwan)
pi@raspberrypi:~/OpenSSL/openssl $
// 原因為編碼錯誤, 下兩個命令可以查詢, 並比較
pi@raspberrypi:~/OpenSSL/openssl $ openssl asn1parse -in androiid/android.csr
pi@raspberrypi:~/OpenSSL/openssl $ openssl asn1parse -in ca/ca.crt
// 修改設定
pi@raspberrypi:~/OpenSSL/openssl $ vi openssl.cnf
#string_mask = utf8only
string_mask = pkix
# For the CA policy
[ policy_match ]
#countryName            = match
#stateOrProvinceName    = match
#organizationName       = match
countryName             = optional
stateOrProvinceName     = optional
organizationName        = optional
organizationalUnitName  = optional
commonName              = supplied
emailAddress            = optional

pi@raspberrypi:~/OpenSSL/openssl $ openssl ca -in android/android.csr -out android/android.crt -days 3650 -cert ca/ca.crt -keyfile ca/ca.key -config openssl.cnf
Using configuration from openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 4 (0x4)
        Validity
            Not Before: Sep  4 05:46:35 2017 GMT
            Not After : Sep  2 05:46:35 2027 GMT
        Subject:
            countryName               = TW
            stateOrProvinceName       = Taiwan
            organizationName          = SDL
            organizationalUnitName    = R&D
            commonName                = AndroidClient
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                99:6F:21:B8:C1:2A:DB:03:7F:37:47:17:F5:C8:6C:10:18:B2:75:50
            X509v3 Authority Key Identifier:
                keyid:F4:6D:3E:3D:93:2A:4A:81:85:62:C3:D7:4B:70:F9:28:F6:E6:A4:F4

Certificate is to be certified until Sep  2 05:46:35 2027 GMT (3650 days)
Sign the certificate? [y/n]:y
failed to update database
TXT_DB error number 2
// 不明原因失敗,下列為解決方法
pi@raspberrypi:~/OpenSSL/openssl $ ls newcerts/
01.pem  02.pem  03.pem
pi@raspberrypi:~/OpenSSL/openssl $ openssl ca -revoke newcerts/03.pem -config op
enssl.cnf -cert ca/ca.crt -keyfile ca/ca.key
Using configuration from openssl.cnf
Revoking Certificate 03.
Data Base Updated
pi@raspberrypi:~/OpenSSL/openssl $
// 重新簽署
pi@raspberrypi:~/OpenSSL/openssl $ openssl ca -in android/android.csr -out android/android.crt -days 3650 -cert ca/ca.crt -keyfile ca/ca.key -config openssl.cnf
Using configuration from openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 4 (0x4)
        Validity
            Not Before: Sep  4 05:51:48 2017 GMT
            Not After : Sep  2 05:51:48 2027 GMT
        Subject:
            countryName               = TW
            stateOrProvinceName       = Taiwan
            organizationName          = SDL
            organizationalUnitName    = R&D
            commonName                = AndroidClient
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                99:6F:21:B8:C1:2A:DB:03:7F:37:47:17:F5:C8:6C:10:18:B2:75:50
            X509v3 Authority Key Identifier:
                keyid:F4:6D:3E:3D:93:2A:4A:81:85:62:C3:D7:4B:70:F9:28:F6:E6:A4:F4

Certificate is to be certified until Sep  2 05:51:48 2027 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
pi@raspberrypi:~/OpenSSL/openssl $

//將 ca.crt 和 android.crt 傳回 PC
// 安裝根證書
D:\SVN_Repository3\pi\Key>"C:\Program Files\Java\jdk1.7.0_67\bin\keytool.exe" -import -trustcacerts -v -alias ca -file ca.crt -keystore android.jks -storepass store1234
擁有者: CN=PiCA, OU=R&D, O=SDL, L=Taichung, ST=Taiwan, C=TW
發出者: CN=PiCA, OU=R&D, O=SDL, L=Taichung, ST=Taiwan, C=TW
序號: e595993377a61f60
有效期自: Tue Aug 29 09:40:37 CST 2017 到: Fri Aug 27 09:40:37 CST 2027
憑證指紋:
         MD5:  8D:94:79:EB:E6:81:8C:33:4F:BE:7C:EF:16:D3:23:28
         SHA1: 7B:DF:78:14:87:F1:C8:DA:27:91:9B:6C:B7:7C:B6:6C:3F:84:59:13
         SHA256: 38:C6:7B:DC:DB:28:EA:CC:6A:A0:38:4B:DF:D2:D6:B2:44:70:CE:B5:86:F0:DE:9B:99:49:3C:75:D6:5C:89:EB
         簽章演算法名稱: SHA256withRSA
         版本: 3

擴充套件:

#1: ObjectId: 2.5.29.35 Criticality=false
AuthorityKeyIdentifier [
KeyIdentifier [
0000: F4 6D 3E 3D 93 2A 4A 81   85 62 C3 D7 4B 70 F9 28  .m>=.*J..b..Kp.(
0010: F6 E6 A4 F4                                        ....
]
]

#2: ObjectId: 2.5.29.19 Criticality=false
BasicConstraints:[
  CA:true
  PathLen:2147483647
]

#3: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: F4 6D 3E 3D 93 2A 4A 81   85 62 C3 D7 4B 70 F9 28  .m>=.*J..b..Kp.(
0010: F6 E6 A4 F4                                        ....
]
]

信任這個憑證? [否]:  y
憑證已新增至金鑰儲存庫中
[儲存 android.jks]

D:\SVN_Repository3\pi\Key>
// 安裝證書
D:\SVN_Repository3\pi\Key>"C:\Program Files\Java\jdk1.7.0_67\bin\keytool.exe" -import -v -alias android -file android.crt -keystore android.jks -storepass store1234 -keypass key1234
憑證回覆已安裝在金鑰儲存庫中
[儲存 android.jks]

D:\SVN_Repository3\pi\Key>
// 產生 BKS 格式的 keystore
D:\SVN_Repository3\pi\Key>"C:\Program Files\Java\jdk1.7.0_67\bin\keytool.exe" -importkeystore -srckeystore android.jks -srcstorepass store1234 -destkeystore android.bks -deststoretype BKS -deststorepass store1234 -provider org.bouncycastle.jce.provider.BouncyCastleProvider
已成功匯入別名 ca 的項目。
輸入 <android> 的金鑰密碼
已成功匯入別名 android 的項目。
已完成匯入命令: 成功匯入 2 個項目,0 個項目失敗或已取消

D:\SVN_Repository3\pi\Key>dir
 磁碟區 D 中的磁碟是 新增磁碟區
 磁碟區序號:  3AAA-91FF

 D:\SVN_Repository3\pi\Key 的目錄

2017/09/04  14:39    <DIR>          .
2017/09/04  14:39    <DIR>          ..
2017/09/04  14:39             4,155 android.bks
2017/09/04  13:51             4,417 android.crt
2017/09/04  13:42             1,086 android.csr
2017/09/04  13:52             4,150 android.jks
2017/08/29  09:40             1,289 ca.crt
               5 個檔案          15,097 位元組
               2 個目錄  678,150,561,792 位元組可用

D:\SVN_Repository3\pi\Key>

2017年8月30日 星期三

SSL 網路程式設計

請參考 Raspberry OPENSSL 根證書 伺服端 客戶端 產生所有需要的檔案

sudo apt-get install libssl-dev

伺服器端程式
gcc server.c -o server -lcrypto -lssl
vi server.c
#include "openssl/bio.h"  
#include "openssl/ssl.h"  
#include "openssl/err.h" 

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define SERVER_PORT 8080
#define CA_CERT_FILE "../openssl/ca/ca.crt"
#define SERVER_CERT_FILE "../openssl/server/server.crt"
#define SERVER_KEY_FILE "../openssl/server/server.key"

typedef struct sockaddr SA;

int TcpInit()
{
    int listener;
    do{
        listener = socket(AF_INET, SOCK_STREAM, 0);
        if( listener == -1 )
            return 0;

        struct sockaddr_in sin;
        sin.sin_family = AF_INET;
        sin.sin_addr.s_addr = 0;
        sin.sin_port = htons(SERVER_PORT);

        if( bind(listener, (SA*)&sin, sizeof(sin)) < 0 )
            break;

        if( listen(listener, 5) < 0)
            break;

        return listener;
    }while(0);

    return -1;
}

void print_peer_certificate(SSL *ssl)
{  
    X509* cert= NULL;  
    X509_NAME *name=NULL;  
    char buf[8192]={0};  
    BIO *bio_cert = NULL;  
    cert = SSL_get_peer_certificate(ssl);
    if (cert == NULL) {
        printf("SSL_get_peer_certificate() == NULL\n");  
        return;
    }
    if (SSL_get_verify_result(ssl) == X509_V_OK) {
        printf("SSL_get_verify_result(ssl) == X509_V_OK\n");  
    }
    name = X509_get_subject_name(cert);  
    X509_NAME_oneline(name,buf,8191);  
    printf("ServerSubjectName:%s\n",buf);  
    memset(buf,0,sizeof(buf));  
    bio_cert = BIO_new(BIO_s_mem());  
    PEM_write_bio_X509(bio_cert, cert);  
    BIO_read( bio_cert, buf, 8191);  
    printf("SERVER CERT:\n%s\n",buf);  
    if(bio_cert)BIO_free(bio_cert);  
    if(cert)X509_free(cert);  
}


static int verify_cb(int res, X509_STORE_CTX *xs)  
{  
    printf("SSL VERIFY RESULT :%d\n",res);  
    switch (xs->error)  
    {  
        case X509_V_ERR_UNABLE_TO_GET_CRL:  
            printf(" NOT GET CRL!\n");  
            return 1;  
        default :  
            break;  
    }  
    return res;  
}

int main(int argc, char **argv)  
{  
    SSL_CTX     *ctx;  
    SSL         *ssl;  
    X509        *client_cert;  
    char szBuffer[1024];  
    int nLen;  
    struct sockaddr_in addr;   
    int nListenFd, nAcceptFd;  

    nListenFd = TcpInit();
    SSLeay_add_ssl_algorithms();  
    OpenSSL_add_all_algorithms();  
    SSL_load_error_strings();  
    ERR_load_BIO_strings();  

    memset(&addr, 0, sizeof(addr));
    int len = sizeof(addr);
    nAcceptFd = accept(nListenFd, (struct sockaddr *)&addr, &len);   
    //int iMode = 1;
    //int iret = ioctlsocket(nAcceptFd, FIONBIO, (u_long FAR*)&iMode); 
    ctx = SSL_CTX_new (SSLv23_method());
    if( ctx == NULL)
    {
        printf("SSL_CTX_new error!\n");
        return -1;
    }

#define USE_CA_CERT
#ifdef USE_CA_CERT
// 使用 CA_CERT_FILE 檢查 Client 端的證書
    printf("SSL_CTX_set_verify(SSL_VERIFY_PEER)\n");
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);  

    if(!SSL_CTX_load_verify_locations(ctx, CA_CERT_FILE, NULL))
    {
        printf("SSL_CTX_load_verify_locations error!\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
#else
    printf("SSL_CTX_set_verify(SSL_VERIFY_NONE)\n");
    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);  
#endif

    if(SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM) <= 0)
    {
        printf("SSL_CTX_use_certificate_file error!\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }

    if(SSL_CTX_use_PrivateKey_file(ctx, SERVER_KEY_FILE, SSL_FILETYPE_PEM) <= 0)
    {
        printf("SSL_CTX_use_PrivateKey_file error!\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }

    if(!SSL_CTX_check_private_key(ctx))
    {
        printf("SSL_CTX_check_private_key error!\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
    ssl = SSL_new (ctx);
    if(!ssl)
    {
        printf("SSL_new error!\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
    SSL_set_fd (ssl, nAcceptFd); 
    while(1){
        if(SSL_accept (ssl) != 1)
        {
            int icode = -1;
            ERR_print_errors_fp(stderr);
            int iret = SSL_get_error(ssl, icode);
            printf("SSL_accept error! code = %d, iret = %d\n", icode, iret);
            break;
        } else
            break;
    }
    print_peer_certificate(ssl);

    memset(szBuffer, 0, sizeof(szBuffer));  
    nLen = SSL_read(ssl,szBuffer, sizeof(szBuffer));  
    fprintf(stderr, "Get Len %d %s ok\n", nLen, szBuffer);  
    strcat(szBuffer, "\n this is from server========server resend to client");  
    SSL_write(ssl, szBuffer, strlen(szBuffer));  

    SSL_free (ssl);  
    SSL_CTX_free (ctx);  
    close(nAcceptFd);  
}

客戶端程式
gcc client.c -o client -lcrypto -lssl
vi client.c
#include "openssl/bio.h"  
#include "openssl/ssl.h"  
#include "openssl/err.h" 


#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define SERVER_PORT 8080
#define SERVER_IP "127.0.0.1"


#define CA_CERT_FILE "../openssl/ca/ca.crt"
#define CLIENT_CERT_FILE "../openssl/client/client.crt"
#define CLIENT_KEY_FILE "../openssl/client/client.key"

void print_client_cert(char* path)  
{  
    X509 *cert =NULL;  
    FILE *fp = NULL;  
    fp = fopen(path,"rb");  
    cert = PEM_read_X509(fp, NULL, NULL, NULL);  
    X509_NAME *name=NULL;  
    char buf[8192]={0};  
    BIO *bio_cert = NULL;  
    name = X509_get_subject_name(cert);  
    X509_NAME_oneline(name,buf,8191);  
    printf("ClientSubjectName:%s\n",buf);  
    memset(buf,0,sizeof(buf));  
    bio_cert = BIO_new(BIO_s_mem());  
    PEM_write_bio_X509(bio_cert, cert);  
    BIO_read( bio_cert, buf, 8191);  
    printf("CLIENT CERT:\n%s\n",buf);  
    if(bio_cert)BIO_free(bio_cert);  
    fclose(fp);  
    if(cert) X509_free(cert);  
}

void print_peer_certificate(SSL *ssl)  
{  
    X509* cert= NULL;  
    X509_NAME *name=NULL;  
    char buf[8192]={0};  
    BIO *bio_cert = NULL;  
    cert = SSL_get_peer_certificate(ssl);
    if (cert == NULL) {
        printf("SSL_get_peer_certificate() == NULL\n");
        return;
    }
    if (SSL_get_verify_result(ssl) == X509_V_OK) {
        printf("SSL_get_verify_result(ssl) == X509_V_OK\n");  
    }
    name = X509_get_subject_name(cert);  
    X509_NAME_oneline(name,buf,8191);  
    printf("ServerSubjectName:%s\n",buf);  
    memset(buf,0,sizeof(buf));  
    bio_cert = BIO_new(BIO_s_mem());  
    PEM_write_bio_X509(bio_cert, cert);  
    BIO_read( bio_cert, buf, 8191);  
    printf("SERVER CERT:\n%s\n",buf);  
    if(bio_cert)BIO_free(bio_cert);  
    if(cert)X509_free(cert);  
}

static int verify_cb(int res, X509_STORE_CTX *xs)  
{  
    printf("SSL VERIFY RESULT :%d\n",res);  
    switch (xs->error)  
    {  
        case X509_V_ERR_UNABLE_TO_GET_CRL:  
            printf(" NOT GET CRL!\n");  
            return 1;  
        default :  
            break;  
    }  
    return res;  
}

int main(int argc, char **argv)  
{  
    char *address = SERVER_IP;

    if(argc > 1)
    {
        address = argv[1];
    }

    SSL_METHOD  *meth;  
    SSL_CTX     *ctx;  
    SSL         *ssl;  

    int nFd;  
    int nLen;  
    char szBuffer[1024];  

    SSLeay_add_ssl_algorithms();  
    OpenSSL_add_all_algorithms();  
    SSL_load_error_strings();  
    ERR_load_BIO_strings();  

    print_client_cert(CLIENT_CERT_FILE);

    // 使用SSL V3,V2  
    ctx = SSL_CTX_new (SSLv23_method());
    if( ctx == NULL)
    {
        printf("SSL_CTX_new error!\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }

#define USE_CA_CERT
#ifdef USE_CA_CERT
// 使用 CA_CERT_FILE 檢查 Server 端的證書
    printf("SSL_CTX_set_verify(SSL_VERIFY_PEER)\n");
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_cb);  

    if(!SSL_CTX_load_verify_locations(ctx, CA_CERT_FILE, NULL))
    {
        printf("SSL_CTX_load_verify_locations error!\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
#else
    printf("SSL_CTX_set_verify(SSL_VERIFY_NONE)\n");
    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);  
#endif

#define USE_CERT
#ifdef USE_CERT
    printf("SSL_CTX_use_certificate_file start!\n");
    if(SSL_CTX_use_certificate_file(ctx, CLIENT_CERT_FILE, SSL_FILETYPE_PEM) <= 0)
    {
        printf("SSL_CTX_use_certificate_file error!\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }

    printf("SSL_CTX_use_PrivateKey_file start!\n");
    if(SSL_CTX_use_PrivateKey_file(ctx, CLIENT_KEY_FILE, SSL_FILETYPE_PEM) <= 0)
    {
     printf("SSL_CTX_use_PrivateKey_file error!\n");
     ERR_print_errors_fp(stderr);
     return -1;
    }

    if(!SSL_CTX_check_private_key(ctx))
    {
     printf("SSL_CTX_check_private_key error!\n");
     ERR_print_errors_fp(stderr);
     return -1;
    }
#endif

    nFd = socket(AF_INET, SOCK_STREAM, 0); 

    struct sockaddr_in addr; 
    addr.sin_addr.s_addr = inet_addr(address);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(SERVER_PORT);

    if(connect(nFd, (struct sockaddr *)&addr, sizeof(addr)) < 0)  
    {  
        printf("connect\n"); 
        ERR_print_errors_fp(stderr);
        return -1;  
    }  

    ssl = SSL_new (ctx);
    if( ssl == NULL)
    {
        printf("SSL_new error!\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
    SSL_set_fd (ssl, nFd);  
    if( SSL_connect (ssl) != 1)
    {
        printf("SSL_new error!\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }

    print_peer_certificate(ssl);

    sprintf(szBuffer, "\nthis is from client+++++++++++++++client send to server");  
    SSL_write(ssl, szBuffer, strlen(szBuffer));  

    memset(szBuffer, 0, sizeof(szBuffer));  
    nLen = SSL_read(ssl,szBuffer, sizeof(szBuffer));  
    fprintf(stderr, "Get Len %d %s ok\n", nLen, szBuffer);  

    SSL_free (ssl);  
    SSL_CTX_free (ctx);  
    close(nFd);     
}