2017年6月18日 星期日

Line Bot Message API

之前建一個查字典的Line bot,自從Line Bot更新API後,就一直沒時間更新,趁著這大雨的週日,重新建立Line Bot。

參考 這篇 不必真的架站也能 5 分鐘實機體驗 LINE bot – 教學 ( by node.js & ngrok )
很快的又建立起了Line Bot, 搞定了ECHO功能,很快的就接上之前寫的查字典功能。再加上問天氣的功能,沒時間寫parser,直接就帶出網址點來看。
使用 ngrok 這工具真是方便,用本機就可以直接測試。

最後deploy到Heroku,參考這篇 注意設置PORT轉換,和建立package.json,習慣用command line deploy,可參考Heroku官方文件-Deploying with Git




2016年6月12日 星期日

Github 的遠端檔案操作

新增一個檔案

$ ls > test.txt
$ ls
1 README.md node-crawler.js node_modules result.json test.txt

把檔案加入git

$ git add test.txt
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

new file:   test.txt


對加入檔案的動作下個註解

$ git commit -m 'add test.txt'
[master 1b9d497] add test.txt
 1 file changed, 6 insertions(+)
 create mode 100644 test.txt

$ git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

推送到遠端

$ git push
Counting objects: 3, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 323 bytes | 0 bytes/s, done.
Total 3 (delta 1), reused 0 (delta 0)
To https://github.com/david0932/node-crawler.git
   45e24d1..1b9d497  master -> master









刪除檔案的操作

$ git rm test.txt
rm 'test.txt'

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

deleted:    test.txt

$ git commit -m 'delete test.txt'
[master f6e5af2] delete test.txt
 1 file changed, 6 deletions(-)
 delete mode 100644 test.txt

$ git push
Counting objects: 2, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (2/2), done.
Writing objects: 100% (2/2), 218 bytes | 0 bytes/s, done.
Total 2 (delta 1), reused 0 (delta 0)
To https://github.com/david0932/node-crawler.git
   1b9d497..f6e5af2  master -> master


2016年3月11日 星期五

Real-time weather Information with Onion Omega



Onion Omega是一個使用OpenWRT系統的微型電腦,就用這做個即時天氣小看板。
為了解決中文顯示問題,用了另一台Web Server來解決抓天氣資料和轉換成OLED DATA,Web Server使用PHP和Node.js,Onion Omega 用Python來與Web Server連線與控制OLED。



2015年8月28日 星期五

Node.js with Windows 10 IoT on Raspberry Pi 2

繼續Pi的Windows 10 IoT奇幻旅程,試做Node.js的學習。Follow一些網頁的作法,遇到不少問題,不過,總算是有搞定,做個記錄先。

PC環境設置

  • Install the latest Node.js Tools for Windows IoT from here.
  • Install Python 2.7.


  • Copy Node.js to Pi
    官網是用PowerShell指令操作,有點複雜搞不定,其實用"檔案總管"就可以了。
    將PC上安裝好的Node.js複製到Pi上,再置換node.exe為ARM版本的就好了。



    Build Addon - MemoryStatus
    這程式主要是 node.js 呼叫取得系統中記憶體狀態,需要用到Python 2.7來build.


    Copy Node.js Apps to Pi
    把node.js的執行程式Server.js,和上個步驟所build出來的MemoryStatusAddon.node,copy到Pi。


    Run Node.js App
    這部份就要用PowerShell連到Pi來操作,設定好firewall rule後,就可以執行了。
    用browser連連看…有出現就成功了
    Pi中有Node.js的行程,按X就就可結束

    Reference:
    http://ms-iot.github.io/content/en-US/win10/samples/Nodejs.htm
    http://blogs.windows.com/buildingapps/2015/05/12/bringing-node-js-to-windows-10-iot-core/
    http://ms-iot.github.io/content/en-US/win10/samples/Nodejs.htm
    https://github.com/ms-iot/ntvsiot/releases

    2015年8月26日 星期三

    Raspberry Pi 2 for Windows IoT Core

    Raspberry Pi 2 上跑 Windows IoT Core


    使用Browser連入Pi 2,有相關的裝置資訊和管理介面
    程式App的執行與結束也可透過Web介面管理

    這就像Windows工作管理員一般,顯示執行中的行程
    CPU效能也可在Web上呈現
    也有裝置管理員…cool
    基本網路設定是一定有的,還有藍芽設定
    趕快寫個程式來測試一下,最近剛在做Digital Signage,就用VS 2015寫個Web Browser來連連看





    2014年12月10日 星期三

    2014年7月28日 星期一

    fbi : linux framebuffer imageviewer

    pi@raspberrypi ~ $ sudo fbi -d /dev/fb0 -a -T 2 raspi.png
    using "Droid Sans Fallback-16", pixelsize=16.67 file=/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf
    pi@raspberrypi ~ $ ps -aux |grep fbi
    warning: bad ps syntax, perhaps a bogus '-'?
    See http://gitorious.org/procps/procps/blobs/master/Documentation/FAQ
    root      3991 17.0 12.4  34252 15308 ?        Ss   10:35   0:01 fbi -d /dev/fb0 -a -T 2 raspi.png
    pi        3993  0.0  0.7   3932   880 pts/0    S+   10:35   0:00 grep --color=auto fbi
    pi@raspberrypi ~ $ sudo kill 3991



    pi@raspberrypi ~ $ fbi

    This program displays images using the Linux framebuffer device.
    Supported formats: PhotoCD, jpeg, ppm, gif, tiff, xwd, bmp, png.
    It tries to use ImageMagick's convert for unknown file formats.

    usage: fbi [ options ] file1 file2 ... fileN

        -h  -help               print this help text
        -V  -version            print fbi version number
            -store              write cmd line args to config file
        -l  -list <arg>         read image filelist from file <arg>
        -P  -text               switch into text reading mode
        -a  -autozoom           automagically pick useful zoom factor
            -(no)autoup           like the above, but upscale only
            -(no)autodown         like the above, but downscale only
            -(no)fitwidth         use width only for autoscaling
        -v  -(no)verbose        show filenames all the time
        -u  -(no)random         show files in a random order
        -1  -(no)once           don't loop (for use with -t)
            -(no)comments       display image comments
        -e  -(no)edit           enable editing commands (see man page)
            -(no)backup           create backup files when editing
            -(no)preserve         preserve timestamps when editing
            -(no)readahead      read ahead images into cache
            -cachemem <arg>     image cache size in megabytes
            -blend <arg>        image blend time in miliseconds
        -T  -vt <arg>           start on virtual console <arg>
        -s  -scroll <arg>       scroll image by <arg> pixels
        -t  -timeout <arg>      load next image after <arg> sec without user input
        -r  -resolution <arg>   pick PhotoCD resolution (1..5)
        -g  -gamma <arg>        set display gamma (doesn't work on all hardware)
        -f  -font <arg>         use font <arg> (anything fontconfig accepts)
        -d  -device <arg>       use framebuffer device <arg>
        -m  -mode <arg>         use video mode <arg> (from /etc/fb.modes)

    Large images can be scrolled using the cursor keys.  Zoom in/out
    works with '+' and '-'.  Use ESC or 'q' to quit.  Space and PgDn
    show the next, PgUp shows the previous image. Jumping to a image
    works with <number>g.  Return acts like Space but additionally
    prints the filename of the currently displayed image to stdout.

    reference: http://manpages.ubuntu.com/manpages/lucid/man1/fbi.1.html


    pi@raspberrypi ~ $ sudo fbi -d /dev/fb0 -a -T 2 -t 5 -1 *.png
    --> loop once *.png to /dev/fb0 , and 5 seconds interval to next picture.

    Python get Network IP

    一些取得ip的方法:

    >>> import socket
    >>> def getNetworkIp():
    ...     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ...     s.connect(('www.google.com', 0))
    ...     return s.getsockname()[0]
    ...
    >>> getNetworkIp()
    '192.168.101.253'
    >>>
    -------------------------------------------------------------------------------------
    >>> import socket, struct, fcntl
    >>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    >>> sockfd = sock.fileno()
    >>> SIOCGIFADDR = 0x8915
    >>> def get_ip(iface = 'eth0'):
    ...    ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
    ...    try:
    ...       res = fcntl.ioctl(sockfd, SIOCGIFADDR, ifreq)
    ...    except:
    ...       return None
    ...    ip = struct.unpack('16sH2x4s8x', res)[2]
    ...    return socket.inet_ntoa(ip)
    ...
    >>> get_ip('eth0')
    '192.168.101.253'
    >>>
    iF  Python3 with one modification: struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14) should be replaced with struct.pack('16sH14s', iface.encode('utf-8'), socket.AF_INET, b'\x00'*14)
    -------------------------------------------------------------------------------------
    >>> import commands
    >>> commands.getoutput("/sbin/ifconfig").split("\n")[1].split()[1][5:]
    '192.168.101.253'
    -------------------------------------------------------------------------------------
    #!/usr/bin/python
    # module for getting the lan ip address of the computer

    import os
    import socket

    if os.name != "nt":
        import fcntl
        import struct
        def get_interface_ip(ifname):
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            return socket.inet_ntoa(fcntl.ioctl(
                    s.fileno(),
                    0x8915,  # SIOCGIFADDR
                    struct.pack('256s', ifname[:15])
                )[20:24])

    def get_lan_ip():
        ip = socket.gethostbyname(socket.gethostname())
        if ip.startswith("127.") and os.name != "nt":
            interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"]
            for ifname in interfaces:
                try:
                    ip = get_interface_ip(ifname)
                    break;
                except IOError:
                    pass
        return ip
    print get_lan_ip()
    ----------------------------------------------------------------------------------
    >>> import commands
    >>> ips = commands.getoutput("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | " +"awk {'print $2'} | sed -ne 's/addr\:/ /p'")
    >>> print ips
     192.168.101.253
     127.0.0.1
    >>>
    ---------------------------------------------------------------------------------
    >>> import socket, subprocess, re
    >>> def get_ipv4_address():
    ...     """
    ...     Returns IP address(es) of current machine.
    ...     :return:
    ...     """
    ...     p = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE)
    ...     ifc_resp = p.communicate()
    ...     patt = re.compile(r'inet\s*\w*\S*:\s*(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')
    ...     resp = patt.findall(ifc_resp[0])
    ...     print resp
    ...
    >>> get_ipv4_address()
    ['192.168.101.253', '127.0.0.1']
    >>>

    2014年7月23日 星期三

    Pi的Miracast

    颱風天繼續研究神奇的拍,測試了Piracast,果然神奇~就如Miracat一般,只是beta版不是很穩定~





    2014年7月22日 星期二

    Cython

    Python是直譯式語式,所以執行速度,就較編譯式程式慢,所以有這Cython這個東東,用C語言撰寫後編譯過給python import呼叫。

    Install Cython:
    sudo apt-get install python-pip python-dev
    wget http://pypi.python.org/packages/source/C/Cython/Cython-0.16.tar.gz
    tar xvzf Cython-0.16.tar.gz
    sudo python setup.py install
    ~~~~wait wait wait

    >>> import pyximport; pyximport.install()
    >>> import helloworld
    Hello World



    Cython's Documentation

    2014年7月21日 星期一

    HTTP Live Streaming

    其實今天並沒有要研究HLS,只是要找一個不需掛載任何播放插件的方法,播放網路上的串流。結果找上了HLS就稍後try了一下…

    HTTP Live Streaming (HLS)其實是Apple所制定的,主要是給iOS裝置的safari瀏覽器上播放串流。

    什麼情況下可以使用HLS:
    • Streaming audio or video to iPhone, iPod touch, iPad, or Apple TV
    • Streaming live events without special server software
    • Sending video on demand with encryption and authenticationtt
    Http Live Streaming 的架構其實簡單,主要是將需票串流的檔案切成小片段(.ts),再用一個index file(.m3u8)記錄每個小片段組成播放清單。
    所以需把mp4檔案,切成HLS的架構,所幸ffmpeg就可支援了。

    ffmpeg -y -i taiwan-240p.mp4 -pix_fmt yuv420p -vcodec libx264 -acodec libfaac -r 25 -profile:v baseline -b:v 1500k -maxrate 2000k -force_key_frames 50  -map 0 -flags -global_header -f segment -segment_list ./hls/index.m3u8 -segment_time 10 -segment_format mpeg_ts -segment_list_type m3u8 ./hls/segment%05d.ts

    最後把 index.m3u8 塞給播放端即可。
    居然神奇的pi是可以播Http Live Streaming的格式…太強了。
    Http Live Streaming主要在支援行動裝置播放的,可以直接用HTML5的video tag,給Apple iOS的safari讀取和播放。例如:

    <video  src="http://192.168.101.253/streaming/index.m3u8"   height="300" width="400" controls  > </video>

    測試在iPhone和iPad的safari和chrome都可以播放:


    測試Android 4.4.2的chrome,可以播放,不過剛開始需拉動一下進度bar影像才會出來,不然只有聲音。看來Android的支援度還沒有很完整。



    參考資料:

    [好工具] Nppftp : notepad++的檔案傳輸插件

    如果不是在IDE環境下的coding,最喜歡用notepad++編輯程式了,懷舊的人都喜歡這種傳統的文書編輯器,從pe2到utraledit到notepad++,雖然傳統但是進步許多了,notepad++這國人自製的免費軟體大多數的程式語言都可辨識,尤其是括號的對應,真是太棒的功能。
    最近在linux下coding,一下是php一下是python一下是c,實在用不慣linux下的vi或nano,用了windows的編輯軟體notepad++,又用了Filezilla來傳檔,當然還要開個terminal來操作linux,一下子在好幾個視窗切換,真是好忙…
    最近notepad++開啟時都會跳出有新plug-in通知,Nppftp查了一下是檔案傳輸的插件,二話不說就下載安裝了,果然是好物…以後檔案直接拉下編輯就可以,還支援sftp協定的傳輸,真是方便了。



    2014年7月19日 星期六

    Start a streaming from web

    終於搞定由Web上啟動一個串流播放,一直困擾怎麼把ffmpeg丟到背景執行,搞了一個早上。參考了php:exec上的範例,才搞定這。不過,還不太了解下面這行:
    $command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';
    試過其他的輸出導向都會卡住… 看來這篇文章還要好好研究一下…
    研究了php fork process,原來php也可以fork,有趣了…用PHP寫Multi Process程式




    Internet Streaming


    越玩越起勁了,網路串流整合成功。SRS+FFmpeg+PHP+Video.js+Html5
    FFmpeg – the swiss army knife of Internet Streaming

    This will execute $cmd in the background (no cmd window) without PHP waiting for it to finish, on both Windows and Unix. 

    <?php 
    function execInBackground($cmd) { 
        if (substr(php_uname(), 0, 7) == "Windows"){ 
            pclose(popen("start /B ". $cmd, "r"));  
        } 
        else { 
            exec($cmd . " > /dev/null &");   
        } 
    } 
    ?>




    2014年7月17日 星期四

    Cloud-based Streaming TV

    經過一周又一天的奮鬥,終於搞定了這個基礎架構。解決overlay文字blinking的問題,後來發現是fill display canvas時的問題。這架構用了4支程式3種程式語言,Web介面採用php,Raspberry Pi監控程式使用python,播放器採用內建的omxplayer,文字跑馬燈用C,改自hello_font。串流用了一台Ubuntu使用ffmpeg輸出2個mp4串流,分別是720p和1080p。這個Pi還真是利害,播放1080p影像cpu使用率不到10%。

    2014年7月15日 星期二

    單車。露營。日月潭。

    日月潭環湖最佳的時間一大清早,趁著湖面上與山林間的霧氣還未散去之時。夏日在日月潭週邊露營還算是清涼的,這次露在頭社水庫旁的一個營地,設備真是周全,因此輕裝就出發了。
    營位都有棚架,外帳都可省下,而且還附有桌椅,臨水庫算是清涼的。

    這水庫其實也不算大,走一圈花個20分左右。閒來無事還可拿個釣竿享受魚翁之樂。
    要看這個風景只有起得比雞早啦…

    當然是一群人才好玩~~
    來個有故事的畫面吧…
    藍天、白雲、遊艇,很海邊的感覺...
    還是喜歡玄奘寺旁的觀景台的這個view…美
    來個知名部落客的招牌指天照…
    hApPY eNdiNg

    電話:049-2861497 / 0932-594428
    地址:南投縣魚池鄉頭社村平和巷 127-12 號
    約在台21線環湖公路68K處附近有個「露營烤肉」的牌子一個小坡轉進來,離向山遊客中心很近。



    Pi的串流播放控制

    接續Pi的物聯網,加入omxplayer串流播放控制,網路上找了一些方法有用DBus來控制omxplayer,不過,我只要播放和停止的控制,DBus顯得太過於複雜。後來找到很簡單的方法,就是popen...果然簡單,又符合我的需求...現在可以控制串流播放了。


    2014年7月10日 星期四

    Pi的物聯網

    架構是Pi連網(web) , user連網web控制,不是連到Pi的web server,Pi以USB轉RS-232接LG TV,控制反應時間大概3秒內,Pi的連網程式,使用python語言撰寫,Web server端程式,使用php撰寫。

    這樣應該是有點物聯網的概念了。




    2014年7月9日 星期三

    Raspberry Pi Overlay Text

    今日測試overlay文字…
    用omxplayer 播放影片後,執行 ./hello_font.bin
    發生錯誤訊息並跳出:
    assertion failure:graphics.c:269:gx_priv_restore():egl_result
    找到是GPU memory不足的問題
    $sudo raspi-config
    Advanced Options -> A3 Memory Split -> 128
    順利overlay文字,但是有blink的問題