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

2026年1月6日 星期二

Slimblade pro on ubuntu 22.04

top left to be a toggle button to turn the whole ball into a scroll wheel.
$ gsettings list-recursively org.gnome.desktop.peripherals
org.gnome.desktop.peripherals.keyboard delay uint32 500
org.gnome.desktop.peripherals.keyboard numlock-state false
org.gnome.desktop.peripherals.keyboard remember-numlock-state true
org.gnome.desktop.peripherals.keyboard repeat true
org.gnome.desktop.peripherals.keyboard repeat-interval uint32 30
org.gnome.desktop.peripherals.mouse accel-profile 'default'
org.gnome.desktop.peripherals.mouse double-click 400
org.gnome.desktop.peripherals.mouse drag-threshold 8
org.gnome.desktop.peripherals.mouse left-handed false
org.gnome.desktop.peripherals.mouse middle-click-emulation false
org.gnome.desktop.peripherals.mouse natural-scroll false
org.gnome.desktop.peripherals.mouse speed 0.0
org.gnome.desktop.peripherals.tablet area [0.0, 0.0, 0.0, 0.0]
org.gnome.desktop.peripherals.tablet keep-aspect false
org.gnome.desktop.peripherals.tablet left-handed false
org.gnome.desktop.peripherals.tablet mapping 'absolute'
org.gnome.desktop.peripherals.tablet output ['', '', '']
org.gnome.desktop.peripherals.touchpad click-method 'default'
org.gnome.desktop.peripherals.touchpad disable-while-typing true
org.gnome.desktop.peripherals.touchpad edge-scrolling-enabled false
org.gnome.desktop.peripherals.touchpad left-handed 'mouse'
org.gnome.desktop.peripherals.touchpad middle-click-emulation false
org.gnome.desktop.peripherals.touchpad natural-scroll true
org.gnome.desktop.peripherals.touchpad send-events 'disabled'
org.gnome.desktop.peripherals.touchpad speed 0.0
org.gnome.desktop.peripherals.touchpad tap-and-drag true
org.gnome.desktop.peripherals.touchpad tap-and-drag-lock false
org.gnome.desktop.peripherals.touchpad tap-button-map 'default'
org.gnome.desktop.peripherals.touchpad tap-to-click true
org.gnome.desktop.peripherals.touchpad two-finger-scrolling-enabled true
org.gnome.desktop.peripherals.touchscreen output ['', '', '']
org.gnome.desktop.peripherals.trackball accel-profile 'default'
org.gnome.desktop.peripherals.trackball middle-click-emulation false
org.gnome.desktop.peripherals.trackball scroll-wheel-emulation-button 0
org.gnome.desktop.peripherals.trackball scroll-wheel-emulation-button-lock false

setting
//set
$ gsettings set org.gnome.desktop.peripherals.trackball scroll-wheel-emulation-button 2
$ gsettings set org.gnome.desktop.peripherals.trackball scroll-wheel-emulation-button-lock true


$ gsettings list-recursively org.gnome.desktop.peripherals
...
...
org.gnome.desktop.peripherals.trackball scroll-wheel-emulation-button 2
org.gnome.desktop.peripherals.trackball scroll-wheel-emulation-button-lock true

slimblade_trackball.sh

#!/bin/bash
if lsusb -d 047d:80d6 > /dev/null; then
    # Device found: Enable Emulation
    gsettings set org.gnome.desktop.peripherals.trackball scroll-wheel-emulation-button 2
    gsettings set org.gnome.desktop.peripherals.trackball scroll-wheel-emulation-button-lock true
else
    # Device not found: Disable Emulation
    gsettings set org.gnome.desktop.peripherals.trackball scroll-wheel-emulation-button 0
    gsettings set org.gnome.desktop.peripherals.trackball scroll-wheel-emulation-button-lock false
fi

/etc/udev/rules.d/99-slimblade_trackball.rules

# Run script when the Kensington SlimBlade Pro is added or removed
SUBSYSTEM=="usb", ATTR{idVendor}=="047d", ATTR{idProduct}== "80d6", ACTION=="add", RUN+="/home/ubuntu/.local/bin/slimblade_trackball.sh"
SUBSYSTEM=="usb", ATTR{idVendor}=="047d", ATTR{idProduct}== "80d6", ACTION=="remove", RUN+="/home/ubuntu/.local/bin/slimblade_trackball.sh"

ref:
SlimBlade Linux config

2025年3月4日 星期二

Deleting APN in Network Manager GUI

It works on Ubuntu 22.04
nmcli
$ sudo ls /etc/NetworkManager/system-connections/xxx.nmconnection
$ sudo nmcli connection delete xxx  ( not xxx.nmconnection )
sudo systemctl restart NetworkManager

2024年12月21日 星期六

Neovim+LazyVIM

Neovim, 編譯時,相依滿多東西的,麻煩
a. sudo apt install npm lua-luv-dev lua-lpeg \
   libunibilium-dev libutf8proc-dev libluajit-5.1-dev -y

b. 其它的,缺什麼補什麼
   lua, tree-sitter
   fzf, luarocks(不裝,Checkhealth裡會有WARNING),但它不支援lua 5.5

c. 符號亂碼的話,裝Nerd Font字型:
       nerdfonts
   下載:
       JetBrainsMono Nerd Font
   安裝:
       font
   Terminal:
       要選有Nerd Font的字型,所有符號就能正常下載
       ex: JetBrainsMono Nerd Font
d. (用cmake build...有相依性問題)
   $ make distclean
   $ make CMAKE_BUILD_TYPE=Release
   $ sudo make install

LazyVim
安裝:How to Install

Lazy安裝插件: 剛進去nvim時,壓一下x -> LazyVim Extras, 壓x安裝

Commands for LazyVIM
:checkhealth
:checkhealth mason
:Mason  //初始化 Mason.nvim,通過 mason 可以自動裝各種LSP

Press "i" to install



Color theme ( for nvim -d A_file AA_file )
:colorscheme   ->  tokyonight-moon

$ vim ~/.config/nvim/lua/plugins/colorscheme.lua

return {
  {
    "folke/tokyonight.nvim",
    lazy = false,
    priority = 1000,
    opts = {
      style = "moon", -- 確保固定使用 moon 風格
      on_highlights = function(hl, c)
        hl.DiffChange = { bg = "#7636b0", fg = "NONE", reverse = false, nocombine = true }
        hl.DiffText   = { bg = "#e85050", fg = "#ffffff", bold = true, underline = true, reverse = false, nocombine = true } 
        hl.DiffAdd    = { bg = "#203a26", fg = "NONE", reverse = false, nocombine = true }
        hl.DiffDelete = { bg = "#4a2426", fg = "NONE", reverse = false, nocombine = true }
      end,
    },
  },
}
/home/ubuntu/.config/nvim/stylua.toml
indent_type = "Spaces"
indent_width = 4   //程式縮排設定這個有效
column_width = 120

/home/ubuntu/.config/nvim/lua/config/options.lua
Default options that are always set: 
https://github.com/LazyVim/LazyVim/blob/main/lua/lazyvim/config/options.lua


Quick keyboard map, <leader>:space key
Switch buffer: ]b, [b
Searching for Keywords: <leader> + /

list all symbol: <leader> + c + s/S

keymap corresponds plug-ins
:verbose map <leader>cs

Manually loading clang( after updating to someone version)
:lua require('lspconfig').clangd.setup{} //try two or more times

  • Trace code
  • compile_commands.json, for clangd //A compilation database describes compile commands for a codebase
    放在根專案下
    a. Makefie:
        $ sudo apt install bear
        $ bear -- make
    
    b. CMake:
        $ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 ..
        or
        set(CMAKE_EXPORT_COMPILE_COMMANDS True) at CMakeLists.txt
    
    c. Meson:
        $ meson setup builddir --buildtype debug  //it will create a compile_commands.json in builddir
    
    ex:
    .
    ├── compile_commands.json
    ├── include
    │   └── hello.h
    ├── Makefile
    └── src
        ├── hello.c
        └── main.c
    
    go to implementation(gI),它只會回應:[Fzf-lua] No implementations found

    for kernel
    $ make menuconfig
    
    $ make CC=clang
    
    $ python3 ./scripts/clang-tools/gen_compile_commands.py
    


  • codecompanion
  • Install and Sync
    ~/.config/nvim/lua/plugins/codecompanion.lua
    
    -- lua/plugins/codecompanion.lua
    
    return {
      "olimorris/codecompanion.nvim",
      dependencies = {
        "nvim-lua/plenary.nvim",
        "nvim-treesitter/nvim-treesitter",
        "hrsh7th/nvim-cmp",
        "nvim-telescope/telescope.nvim",
      },
      config = function()
        require("codecompanion").setup({
          strategies = {
            chat = {
              adapter = "ollama_orin",
            },
            inline = {
              adapter = "ollama_orin",
            },
            agent = {
              adapter = "ollama_orin",
            },
          },
          -- This block overrides the default chat behavior globally
          interactions = {
            chat = {
              opts = {
                system_prompt = [[You are an expert AI coding assistant. The user will provide file contents, code snippets, or terminal outputs directly within the chat history using markdown or context tags (like #file or #buffer).
    
    CRITICAL DIRECTION: Always treat this injected text as the literal content of the files. You have full visibility of this data. Never state that you cannot access, view, or read the files provided by the user. If the user asks about a file tagged with #file, look at the text block loaded into the chat context, as that is the file's exact content.
    
    Use Markdown formatting in your answers. When suggesting code changes or new content, use Markdown code blocks. To start a code block, use 4 backticks. After the backticks, add the programming language name as the language ID. To close a code block, use 4 backticks on a new line.]],
              },
            },
          },
          adapters = {
            -- Nesting under 'http' satisfies the internal layout validator
            http = {
              ollama_orin = function()
                -- Extending the native "ollama" preset inside the http block
                -- automatically configures roles, streaming, and correct endpoints
                return require("codecompanion.adapters").extend("ollama", {
                  env = {
                    url = "https://111.222.111.222",
                  },
                  schema = {
                    model = {
                      default = "codestral",
                    },
                    num_ctx = {
                      default = 32768, -- Utilizing the full context window for large log/source files
                    },
                  },
                  opts = {
                    extra_args = { "-k", "-s" }, -- Securely bypasses local self-signed HTTPS blocks
                  },
                })
              end,
            },
          },
        })
    
        -- Keymaps
        local map = vim.keymap.set
        map({ "n", "v" }, "<leader>ac", "<cmd>CodeCompanionChat Toggle<cr>", { desc = "Toggle AI Chat" })
        map({ "n", "v" }, "<leader>aa", "<cmd>CodeCompanionActions<cr>", { desc = "AI Actions Menu" })
        map("v", "<leader>ce", "<cmd>CodeCompanion /explain<cr>", { desc = "Explain Code" })
        map("v", "<leader>ai", ":<C-u>CodeCompanion ", { desc = "Inline AI Prompt" })
      end,
    }
    


  • LintaoAmons/bookmarks.nvim
  • -- with lazy.nvim
    return {
      "LintaoAmons/bookmarks.nvim",
      -- tag = "v4.0.0",
      dependencies = {
        { "kkharji/sqlite.lua" },
        { "nvim-telescope/telescope.nvim" },
        { "stevearc/dressing.nvim" }, -- optional: better UI
      },
      config = function()
        local opts = {} -- go to the following link to see all the options in the deafult config file
        require("bookmarks").setup(opts) -- you must call setup to init sqlite db
      end,
      keys = {
        { "mm", "<cmd>BookmarksMark<cr>", desc = "Mark current line into active BookmarkList", mode = { "n", "v" } },
        { "mo", "<cmd>BookmarksGoto<cr>", desc = "Go to bookmark at current active BookmarkList", mode = { "n", "v" } },
        { "ml", "<cmd>BookmarksTree<cr>", desc = "Browse bookmarks in tree view", mode = { "n", "v" } },
      },
    }
    
    -- run :BookmarksInfo to see the running status of the plugin
    
    ~/.local/share/nvim/bookmarks.backup/bookmarks_yyyymmdd.sqlite.db,一個約16kB
    ~/.local/share/nvim/bookmarks.sqlite.db

  • dap
  • GDB, at least version 14+
    ~/.local/share/nvim/lazy/LazyVim/lua/lazyvim/plugins/extras/dap/core.lua
    ...
    keys = {
          { "<leader>dB", function() require("dap").set_breakpoint(vim.fn.input('Breakpoint condition: ')) end, desc = "Breakpoint Condition" },
          { "<leader>db", function() require("dap").toggle_breakpoint() end, desc = "Toggle Breakpoint" },
          { "<leader>dc", function() require("dap").continue() end, desc = "Run/Continue" },
    ...
    
    Useage:
    $ gdb -g -Wall gdb_test.c -o gdb_test
    
    lazynvim:
    a. key: <leader>db, //toggle breakpoing
    b. start: <leader>da  //Lanuch file -> Run with args(enter) -> Patch to executable (enter gdb_test)
    

  • 內建bookmark
  • Delete: :delmarks a-z   or  :delmarks!
    

  • 莫名升到nvim 0.11後就有問題了, 再用最新版的build後就沒了, 14fb5b1c79f8d9fca5a8f2b341cf6fa2bb775540, NVIM v0.12.0-dev-213+g1670fbee0f
  • ~/.local/share/nvim/lazy/nui.nvim/lua/nui/utils/init.lua:379: Unknown option 'winborder'
    先把這段程式註記掉...
    -- if _.feature.v0_11 then
    --   function _.get_default_winborder()
    --     local style = vim.api.nvim_get_option_value("winborder", {})
    --     if style == "" then
    --       return "none"
    --     end
    --     return style
    --   end
    -- end
    
ref:
1. keymaps
2. 使用LazyVim将Neovim打造成强大IDE(常用快捷键)
3. gemini.nvim

2024年3月12日 星期二

16.04要用22.04 apt source碰到key的問題

The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 871920D1991BC93C
NO_PUBKEY 871920D1991BC93C
$ sudo apt-get update
Hit:1 http://tw.archive.ubuntu.com/ubuntu bionic InRelease
Hit:2 http://tw.archive.ubuntu.com/ubuntu bionic-updates InRelease
Hit:3 http://tw.archive.ubuntu.com/ubuntu bionic-backports InRelease
Get:4 http://mirrors.163.com/ubuntu jammy InRelease [270 kB]
Hit:5 http://security.ubuntu.com/ubuntu bionic-security InRelease
Err:4 http://mirrors.163.com/ubuntu jammy InRelease
  The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 871920D1991BC93C
...
...
...

Didn't work
$ sudo apt-key adv --keyserver keys.gnupg.net --recv-keys 871920D1991BC93C
Executing: /tmp/apt-key-gpghome.SPEq7suR5V/gpg.1.sh --keyserver keys.gnupg.net --recv-keys 871920D1991BC93C
gpg: keyserver receive failed: No name

It works.
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com --recv 871920D1991BC93C
[sudo] password for ubuntu:
Executing: /tmp/apt-key-gpghome.1L20qFwiJG/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com --recv 871920D1991BC93C
gpg: key 871920D1991BC93C: 4 signatures not checked due to missing keys
gpg: key 871920D1991BC93C: public key "Ubuntu Archive Automatic Signing Key (2018) <ftpmaster@ubuntu.com>" imported
gpg: Total number processed: 1
gpg:               imported: 1

2023年12月11日 星期一

smp_affinity, taskset and isolcpus 指定CPU方法

  • smp_affinity
    MV31是走USB介面,用lsusb查看,是用xhci_hcd
    $ lsusb
    Bus 004 Device 002: ID 1e2d:00b3 Gemalto M2M GmbH Cinterion PID 0x00B3 USB Mobile Broadband
    Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    
    $ lsusb -t
    /:  Bus 04.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/8p, 20000M/x2
        |__ Port 2: Dev 2, If 0, Class=Communications, Driver=cdc_mbim, 5000M
        |__ Port 2: Dev 2, If 1, Class=CDC Data, Driver=cdc_mbim, 5000M
        |__ Port 2: Dev 2, If 2, Class=Vendor Specific Class, Driver=option, 5000M
        |__ Port 2: Dev 2, If 3, Class=Vendor Specific Class, Driver=, 5000M
        |__ Port 2: Dev 2, If 4, Class=Vendor Specific Class, Driver=option, 5000M
        |__ Port 2: Dev 2, If 5, Class=Vendor Specific Class, Driver=option, 5000M
    
    

    查下中斷表是否有xhci_hcd
    $ cat /proc/interrupts | grep -i xhci_hcd
     130:          0          0          0          0          0          0          0          0          0          0          0          0          0          0          0          0  IR-PCI-MSI-0000:00:0d.0    0-edge      xhci_hcd
     132:          0        537          0          0          0          0          0          0          0          0          0          0          0      19774          0          0  IR-PCI-MSI-0000:00:14.0    0-edge      xhci_hcd
    

    中斷號碼132看起來在CPU13用得比較多(19774)
    用ping再度確認下
    CPU13變高到25209
    $ ping -I wwan0 8.8.8.8
    PING 8.8.8.8 (8.8.8.8) from 10.238.24.92 wwan0: 56(84) bytes of data.
    64 bytes from 8.8.8.8: icmp_seq=1 ttl=55 time=41.2 ms
    64 bytes from 8.8.8.8: icmp_seq=2 ttl=55 time=23.8 ms
    64 bytes from 8.8.8.8: icmp_seq=3 ttl=55 time=37.3 ms
    ^C
    --- 8.8.8.8 ping statistics ---
    3 packets transmitted, 3 received, 0% packet loss, time 2003ms
    rtt min/avg/max/mdev = 23.798/34.110/41.199/7.460 ms
    
    $ cat /proc/interrupts | grep -i xhci_hcd
     130:          0          0          0          0          0          0          0          0          0          0          0          0          0          0          0          0  IR-PCI-MSI-0000:00:0d.0    0-edge      xhci_hcd
     132:          0        537          0          0          0          0          0          0          0          0          0          0          0      25209          0          0  IR-PCI-MSI-0000:00:14.0    0-edge      xhci_hcd
    

    系統用哪顆CPU來處理這個中斷
    $ cat /proc/irq/132/smp_affinity
    2020
    

    試著改變到CPU14和CPU15,並用PING再測試
    # echo "c000" > /proc/irq/132/smp_affinity
    
    # cat /proc/irq/132/smp_affinity
    c000
    
    $ cat /proc/interrupts | grep -i xhci_hcd
     130:          0          0          0          0          0          0          0          0          0          0          0          0          0          0          0          0  IR-PCI-MSI-0000:00:0d.0    0-edge      xhci_hcd
     132:          0        537          0          0          0          0          0          0          0          0          0          0          0      35409       1373          0  IR-PCI-MSI-0000:00:14.0    0-edge      xhci_hcd
    

    queues
    $ cd /sys/class/net/wwan0/queues
    $ tree -L 1
    .
    ├── rx-0
    └── tx-0
    
    $ cat rx-0/rps_cpus
    0000  //這個值也能調整來提高效率
    

  • taskset
    Install:
    $ sudo apt-get install util-linux
    

    查訊程式用哪顆CPU處理
    $ taskset -p PID
    $ taskset -p 6151
    pid 6151's current affinity mask: ffff
    

    指定程式用哪顆CPU處理
    $ taskset 8 /usr/local/bin/my_programer
    or
    $ taskset -p CPU_number PID
    
    $ taskset -p c000 6195
    pid 6195's current affinity mask: ffff
    pid 6195's new affinity mask: c000
    


  • isolcpus尚末使用


ref:
1. [转]再转载一篇关于SMP IRQ affinity的好文章(包含RPS/RFS)
2. CPU Affinity taskset (cpuset)
3. 在 Linux 中以特定的 CPU 核心執行程式

2023年10月12日 星期四

Glibc

Check glibc version
$ ldd --version
$ ldd --version
ldd (Ubuntu GLIBC 2.35-0ubuntu3) 2.35
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Written by Roland McGrath and Ulrich Drepper.


or

$ strings /lib/x86_64-linux-gnu/libc.so.6 | grep -i GLIBC_
...
...
GLIBC_2.33
GLIBC_2.34
GLIBC_2.35
GLIBC_PRIVATE
...
...

Current glibc version support list
use the link to search
focal: 2.31
jammy: 2.35
...
...

modity the file: /etc/apt/sources.list

$ sudo apt update
$ sudo apt install libc6


install gcc
sudo apt-get install gcc-9 g++-9
$ sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 60 --slave /usr/bin/g++ g++ /usr/bin/g++-9
$ sudo update-alternatives --config gcc

2023年6月7日 星期三

Gnome shell extension

Ubuntu 22.04

Install Gnome extension in Chrome browser


Install extension manager
sudo apt-get install gnome-shell-extension-prefs gnome-shell-extensions gnome-shell-extension-manager

Check Gnome version
$ gnome-shell --version
GNOME Shell 42.5

The program installation location
~/.local/share/gnome-shell/extensions

Extensions
  • Tile windows on a grid.
Tactile
keyboard:  super +  T

Press 'Q' twice

2022年10月18日 星期二

Darknet with CUDA for AORUS

Xubuntu 20.4


環境: i7-11800H + RTK3070
Ubuntu 22.04.1, 5.15.0-43-generic, gcc:11, cmake:3.23, python:3.10
安裝好22.04.1,CUDA也裝好了,如下:
 $ nvidia-smi
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 515.65.01    Driver Version: 515.65.01    CUDA Version: 11.7     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|                               |                      |               MIG M. |
|===============================+======================+======================|
|   0  NVIDIA GeForce ...  Off  | 00000000:01:00.0 Off |                  N/A |
| N/A   39C    P0    N/A /  N/A |      5MiB /  8192MiB |      0%      Default |
|                               |                      |                  N/A |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                                  |
|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |
|        ID   ID                                                   Usage      |
|=============================================================================|
|    0   N/A  N/A      2334      G   /usr/lib/xorg/Xorg                  4MiB |
+-----------------------------------------------------------------------------+

安裝 CUDA 11.7 tool-kit (裝11.8,無法開機@@)
$ wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin
$ sudo mv cuda-ubuntu2204.pin /etc/apt/preferences.d/cuda-repository-pin-600
$ wget https://developer.download.nvidia.com/compute/cuda/11.7.1/local_installers/cuda-repo-ubuntu2204-11-7-local_11.7.1-515.65.01-1_amd64.deb
$ sudo dpkg -i cuda-repo-ubuntu2204-11-7-local_11.7.1-515.65.01-1_amd64.deb
$ sudo cp /var/cuda-repo-ubuntu2204-11-7-local/cuda-*-keyring.gpg /usr/share/keyrings/
$ sudo apt-get update
$ sudo apt-get -y install cuda
裝好後,重開機看是否能正常開機,也確認nvidia-smi正常
安裝CUDNN (下載,需另外註冊,要配合 CUDA 版本)
cudnn-linux-x86_64-8.5.0.96_cuda11-archive.tar.xz

$ sudo cp include/* /usr/local/cuda-11/include
$ sudo cp -d lib/* /usr/local/cuda-11/lib64

edit .bashrc
export PATH=$PATH:/usr/local/cuda-11/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-11/lib64                
export CUDADIR=/usr/local/cuda-11
export CUDA_HOME=/usr/local/cuda-11



OpenCV (latest ver: 4.6), refer to Here
$ sudo apt install libgtk2.0-dev ffmpeg \
pkg-config libjpeg-dev libpng-dev libtiff-dev \
libavcodec-dev libavformat-dev libswscale-dev \
libv4l-dev libxvidcore-dev libgtk-4-dev libcanberra-gtk-module libcanberra-gtk3-module \
libx264-dev libatlas-base-dev gfortran


$ mkdir build; cd build
$ cmake {...} -D CMAKE_BUILD_TYPE=RELEASE \
  -D CMAKE_INSTALL_PREFIX=/usr/local/opencv \
  -D INSTALL_C_EXAMPLES=OFF \
  -D INSTALL_PYTHON_EXAMPLES=ON \
  -D BUILD_EXAMPLES=ON \
  -D WITH_CUDA=ON \
  -D WITH_CUDNN=ON \
  -D WITH_OPENCL=ON \
  -D OPENCV_DNN_CUDA=ON \
  -D WITH_VA=OFF \ (編譯時,有gapi/VA_INCLUDE_DIR的問題, ref: Here)
  -D WITH_GTK=ON \
  -D WITH_GTK_2_X=ON \
  -D OPENCV_EXTRA_MODULES_PATH=/home/ubuntu/Projector/opencv/opencv_contrib/modules \
  -D PYTHON2_EXECUTABLE= \
  -D BUILD_OPENCV_PYTHON3=yes \
  -D PYTHON3_EXECUTABLE=/usr/bin/python3.10 \
  -D PYTHON3_INCLUDE_DIR=/usr/include/python3.10 \
  -D PYTHON3_INCLUDE_DIR2=/usr/include/python3.10 \
  -D PYTHON3_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.10.so \
  -D PYTHON3_NUMPY_INCLUDE_DIRS=/home/ubuntu/.local/lib/python3.10/site-packages/numpy/core/include \
  -D PYTHON3_PACKAGES_PATH=/home/ubuntu/.local/lib/python3.10/site-packages \
  -D OPENCV_GENERATE_PKGCONFIG=YES \
  -D WITH_TENGINE=ON \
  -D OPENCV_ENABLE_NONFREE:BOOL=ON ..
  
$ make (約3小時多)
$ sudo make install
opencv.pc
$ cd /usr/local/lib/pkgconfig
$ sudo ln -s /usr/local/opencv/lib/pkgconfig/opencv4.pc opencv.pc



Darknet
下載:
$ git clone https://github.com/pjreddie/darknet.git
修改Makefile: ( compute_xx查詢 )
GPU=1
CUDNN=1
OPENCV=1
OPENMP=0
DEBUG=0

ARCH= -gencode arch=compute_86,code=sm_86
弄錯的話,會有no kernel image is available for execution on the device的問題
修改src/convolutional_layer.c
...
...

#define PRINT_CUDNN_ALGO 0
#define MEMORY_LIMIT 2000000000

...
...
     #if CUDNN_MAJOR >= 7
     cudnnSetConvolutionGroupCount(l->convDesc, l->groups);
     #else
     if(l->groups > 1){
         error("CUDNN < 7 doesn't support groups, please upgrade!");
     }
     #endif
 
 	
    #if CUDNN_MAJOR >= 8
    int returnedAlgoCount;
    cudnnConvolutionFwdAlgoPerf_t       fw_results[2 * CUDNN_CONVOLUTION_FWD_ALGO_COUNT];
    cudnnConvolutionBwdDataAlgoPerf_t   bd_results[2 * CUDNN_CONVOLUTION_BWD_DATA_ALGO_COUNT];
    cudnnConvolutionBwdFilterAlgoPerf_t bf_results[2 * CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT];
 
    cudnnFindConvolutionForwardAlgorithm(cudnn_handle(),
            l->srcTensorDesc,
            l->weightDesc,
            l->convDesc,
            l->dstTensorDesc,
            CUDNN_CONVOLUTION_FWD_ALGO_COUNT,
            &returnedAlgoCount,
	    fw_results);
    for(int algoIndex = 0; algoIndex < returnedAlgoCount; ++algoIndex){
        #if PRINT_CUDNN_ALGO > 0
        printf("^^^^ %s for Algo %d: %f time requiring %llu memory\n",
               cudnnGetErrorString(fw_results[algoIndex].status),
               fw_results[algoIndex].algo, fw_results[algoIndex].time,
               (unsigned long long)fw_results[algoIndex].memory);
        #endif
        if( fw_results[algoIndex].memory < MEMORY_LIMIT ){
            l->fw_algo = fw_results[algoIndex].algo;
            break;
	}
    }
 
    cudnnFindConvolutionBackwardDataAlgorithm(cudnn_handle(),
            l->weightDesc,
            l->ddstTensorDesc,
            l->convDesc,
            l->dsrcTensorDesc,
            CUDNN_CONVOLUTION_BWD_DATA_ALGO_COUNT,
            &returnedAlgoCount,
            bd_results);
    for(int algoIndex = 0; algoIndex < returnedAlgoCount; ++algoIndex){
        #if PRINT_CUDNN_ALGO > 0
        printf("^^^^ %s for Algo %d: %f time requiring %llu memory\n",
               cudnnGetErrorString(bd_results[algoIndex].status),
               bd_results[algoIndex].algo, bd_results[algoIndex].time,
               (unsigned long long)bd_results[algoIndex].memory);
        #endif
        if( bd_results[algoIndex].memory < MEMORY_LIMIT ){
            l->bd_algo = bd_results[algoIndex].algo;
            break;
        }
    }
 
    cudnnFindConvolutionBackwardFilterAlgorithm(cudnn_handle(),
            l->srcTensorDesc,
            l->ddstTensorDesc,
            l->convDesc,
            l->dweightDesc,
            CUDNN_CONVOLUTION_BWD_FILTER_ALGO_COUNT,
            &returnedAlgoCount,
            bf_results);
    for(int algoIndex = 0; algoIndex < returnedAlgoCount; ++algoIndex){
        #if PRINT_CUDNN_ALGO > 0
        printf("^^^^ %s for Algo %d: %f time requiring %llu memory\n",
               cudnnGetErrorString(bf_results[algoIndex].status),
               bf_results[algoIndex].algo, bf_results[algoIndex].time,
               (unsigned long long)bf_results[algoIndex].memory);
        #endif
        if( bf_results[algoIndex].memory < MEMORY_LIMIT ){
            l->bf_algo = bf_results[algoIndex].algo;
            break;
        }
    }
 	
    #else
    
         cudnnGetConvolutionForwardAlgorithm(cudnn_handle(),
              l->srcTensorDesc,
              l->weightDesc,
              l->convDesc,
              l->dstTensorDesc,
              CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT,
              2000000000,
              &l->fw_algo);
    ...
    ...
    
    #endif
    
...
...
...
...
[SOLVED] "Error: 'IplImage' does not name a type when trying to build darknet with
$ git diff src/image_opencv.cpp
diff --git a/src/image_opencv.cpp b/src/image_opencv.cpp
index 7511280..1b0d7b6 100644
--- a/src/image_opencv.cpp
+++ b/src/image_opencv.cpp
@@ -5,6 +5,11 @@
 #include "opencv2/opencv.hpp"
 #include "image.h"

+#include "opencv2/core/core_c.h"
+#include "opencv2/videoio/legacy/constants_c.h"
+#include "opencv2/highgui/highgui_c.h"
+
+
 using namespace cv;

 extern "C" {
@@ -60,7 +65,8 @@ Mat image_to_mat(image im)

 image mat_to_image(Mat m)
 {
-    IplImage ipl = m;
+    //IplImage ipl = m;
+    IplImage ipl = cvIplImage(m) ;
測試:
$ wget https://pjreddie.com/media/files/yolov3.weights
$ ./darknet detect cfg/yolov3.cfg yolov3.weights data/dog.jpg

2022年5月4日 星期三

MQTT server and generate the CA and PEM convert DER

環境: XUbuntu20.04

MQTT Server
  • 安裝
  • sudo apt-get install mosquitto
    
  • Certification for Server and Client
  • Step 1: Create a Certificate Authority (CA):
    
        a. Generate a private key for the CA:
           $ openssl genpkey -algorithm RSA -out ca.key
    
        b. Create a self-signed certificate for the CA:
           $ openssl req -x509 -new -key ca.key -out ca.crt
    
    Step 2: Create Server Certificate and Key
    
        a. Generate a private key for the server:
           $ openssl genpkey -algorithm RSA -out server.key
    
        b. Create a Certificate Signing Request (CSR) for the server:
           $ openssl req -new -key server.key -out server.csr
           Common Name (CN) Matching:
           Make sure that the Common Name (CN) in the server certificate matches the hostname or IP address used to connect to the MQTT broker. 
           If you are connecting to 127.0.0.1, the CN should be set to 127.0.0.1 in the server certificate.
    
        c. Sign the server CSR with the CA:
           $ openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt
    
    Step 3: Create Client Certificate and Key
    
        a. Generate a private key for the client:
           $ openssl genpkey -algorithm RSA -out client.key
    
        b. Create a Certificate Signing Request (CSR) for the client:
           $ openssl req -new -key client.key -out client.csr
    
        c. Sign the client CSR with the CA:
           $ openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt
    
    
    $ tree 
    ├── ca.crt
    ├── ca.key
    ├── client.crt
    ├── client.csr
    ├── client.key
    ├── server.crt
    ├── server.csr
    └── server.key
    
    $ chmod 644 *.crt *.key *.csr
    
    $ sudo cp ca.* server.* /etc/mosquitto/certs/
    ref:
    1. ChatGPT 3.5
    2. ref: 如何自动创建Mosquitto的TLS证书?
    3. https://segmentfault.com/a/1190000014250065
  • 設定
  • sudo vim /etc/mosquitto/conf.d/default.conf (create default.conf by myself)
    
    listener 8883
    protocol mqtt
    cafile   /etc/mosquitto/certs/ca.crt
    certfile /etc/mosquitto/certs/server.crt
    keyfile  /etc/mosquitto/certs/server.key
    allow_anonymous true
    require_certificate false
    #tls_version tlsv1.2
    log_type debug
    require_certificate false
    
  • Start Server
  • $ sudo systemctl stop mosquitto.service
    $ mosquitto -c /etc/mosquitto/conf.d/default.conf -v   //easy debug
    
    or
    
    $ sudo systemctl restart mosquitto.service
    


MQTT Publish/Subscribe for client
  • 測試
  • $ mosquitto_sub -h 127.0.0.1 -p 8883 -t 'test/topic' --cafile ./ca.crt --cert ./client.crt --key ./client.key -q 1
    
    $ mosquitto_pub -h 127.0.0.1 -p 8883 -t 'test/topic' -m hello_world -p 8883 --cafile ./ca.crt --cert ./client.crt --key ./client.key -q 1
    
    or
    
    $ mosquitto_sub -h 127.0.0.1 -p 8883 -t 'test/topic' --cafile ./ca.crt -q 1
    
    $ mosquitto_pub -h 127.0.0.1 -p 8883 -t 'test/topic' -m hello_world -p 8883 --cafile ./ca.crt -q 1
    



PEM convert DER (還沒在 EXS82-W 上試過, 不能連區網...)
$ openssl x509 -req -in client.csr -inform PEM -signkey ca.key -out client.der -outform DER -days 364

2022年3月15日 星期二

etc/network/interfaces at Ubuntu 20.04

環境: xubuntu 20.04


有點久沒看到 /etc/network/interfaces了,Xubuntu20.04預設是沒有
Ubuntu 從 17.10 版開始使用 Netplan 作為系統預設的網路設定方式
要安裝 ifupdown 才會有 /etc/network/interfaces.d/
新增設定interfaces也才會有效
$ sudo apt-get install ifupdown

新增設定interfaces
$ sudo vim /etc/network/interfaces

iface wlan0 inet manual

auto wwxxxx (先用 ifconfig 確認 interface_name)
iface wwxxxx inet dhcp
  pre-up /usr/sbin/chat -f /etc/chatscripts/wwan-up -v < /dev/ttyACM0 > /dev/ttyACM0  (for PLS8)
  down   /usr/sbin/chat -f /etc/chatscripts/wwan-down -v < /dev/ttyACM0 > /dev/ttyACM0 (for PLS8)


然後
$ sudo service network-manager restart


沒試過:
1. 使用 Netplan 進行 Ubuntu 的網路卡設定
2. How to Configure Networking in Ubuntu 20.04 with NetPlan

2021年9月23日 星期四

AP mode for Wifi on Ubuntu


iw list to check if it support AP mode.
$ iw list
...
...
Supported interface modes:
               * IBSS
               * managed
               * AP
               * P2P-client
               * P2P-GO
...
...

//It supports the Frequencies
iw list | grep -A20 Frequencies
$ iw list | grep -A20 Frequencies
                Frequencies:
                        * 2412 MHz [1] (20.0 dBm)
                        * 2417 MHz [2] (20.0 dBm)
                        * 2422 MHz [3] (20.0 dBm)
                        * 2427 MHz [4] (20.0 dBm)
                        * 2432 MHz [5] (20.0 dBm)
                        * 2437 MHz [6] (20.0 dBm)
                        * 2442 MHz [7] (20.0 dBm)
                        * 2447 MHz [8] (20.0 dBm)
                        * 2452 MHz [9] (20.0 dBm)
                        * 2457 MHz [10] (20.0 dBm)
                        * 2462 MHz [11] (20.0 dBm)
                        * 2467 MHz [12] (20.0 dBm) (no IR)
                        * 2472 MHz [13] (20.0 dBm) (no IR)
                        * 2484 MHz [14] (disabled)
        Band 2:
                Capabilities: 0x863
                        RX LDPC
                        HT20/HT40
                        Static SM Power Save
                        RX HT20 SGI
--
                Frequencies:
                        * 5180 MHz [36] (20.0 dBm)
                        * 5200 MHz [40] (20.0 dBm)
                        * 5220 MHz [44] (20.0 dBm)
                        * 5240 MHz [48] (20.0 dBm)
                        * 5260 MHz [52] (20.0 dBm) (no IR)
                        * 5280 MHz [56] (20.0 dBm) (no IR)
                        * 5300 MHz [60] (20.0 dBm) (no IR)
                        * 5320 MHz [64] (20.0 dBm) (no IR)
                        * 5500 MHz [100] (20.0 dBm) (no IR)
                        * 5520 MHz [104] (20.0 dBm) (no IR)
                        * 5540 MHz [108] (20.0 dBm) (no IR)
                        * 5560 MHz [112] (20.0 dBm) (no IR)
                        * 5580 MHz [116] (20.0 dBm) (no IR)
                        * 5600 MHz [120] (20.0 dBm) (no IR)
                        * 5620 MHz [124] (20.0 dBm) (no IR)
                        * 5640 MHz [128] (20.0 dBm) (no IR)
                        * 5660 MHz [132] (20.0 dBm) (no IR)
                        * 5680 MHz [136] (20.0 dBm) (no IR)
                        * 5700 MHz [140] (20.0 dBm) (no IR)
                        * 5720 MHz [144] (disabled)


use nmcli to enable, nmcli version: 1.36.6
$ sudo nmcli d wifi hotspot ifname "wifi-if-name" ssid "ssid-name" password "ssid-passwd"

ex:
$ sudo nmcli d wifi hotspot ifname wlan0 ssid TestHop password 12345678
[sudo] password for nvidia:

Device 'wlan0' successfully activated with '....................'.
Hint: "nmcli dev wifi show-password" shows the Wi-Fi name and password.
nvidia@tegra-ubuntu:~
$ nmcli connection show
NAME                UUID                                  TYPE      DEVICE
Hotspot             ....................................  wifi      wlan0
l4tbr0              ....................................  bridge    l4tbr0
Wired connection 1  ....................................  ethernet  --

It can set more parameters.
$ sudo nmcli connection add type wifi ifname wlP1p1s0 con-name MyAP autoconnect no ssid TestHop
Connection 'MyAP' (f57dec29-c426-4942-ad02-0931587e72dc) successfully added.

$ sudo nmcli connection modify MyAP 802-11-wireless.mode ap

$ sudo nmcli connection modify MyAP 802-11-wireless.band a   //a: 5G, bg: 2.4

$ sudo nmcli connection modify MyAP 802-11-wireless.channel 36  //5G channel

$ sudo nmcli connection modify MyAP 802-11-wireless-security.key-mgmt wpa-psk

$ sudo nmcli connection modify MyAP 802-11-wireless-security.psk "12345678"

$ sudo nmcli connection up MyAP
Error: Connection activation failed: IP configuration could not be reserved (no available address, timeout, etc.)
Hint: use 'journalctl -xe NM_CONNECTION=f57dec29-c426-4942-ad02-0931587e72dc + NM_DEVICE=wlP1p1s0' to get more details.


$ sudo nmcli connection modify MyAP ipv4.method shared

$ sudo nmcli connection modify MyAP ipv6.method ignore

$ sudo nmcli connection up MyAP
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/4)

Deleting APN in Network Manager GUI
$ sudo ls /etc/NetworkManager/system-connections/xxx.nmconnection
$ sudo nmcli connection delete xxx_name
$ sudo systemctl restart NetworkManager
/*nice*/