Raspberry Pi - Adafruit PiUART

OS/Raspberry Pi 2017.09.20 22:28 Posted by 파란크리스마스

출처 : Overview | Adafruit PiUART - USB Console and Power Add-on for Raspberry Pi | Adafruit Learning System
USB to UART Bridge VCP Drivers | Silicon Labs

Adafruit PiUART

PiUART는 Pi의 헤더에 꼽고 Micro 5Pin 케이블을 PC에 연력하면 쉽게 Serial 연결이 됩니다.

LAN연결 없이 터미널에 접속해서 Wifi나 유선LAN의 IP을 확인하는데 유용한 한것 같아 소개합니다.

두 개의 LED가 RX 및 TX에 연결되어 데이터를 보내거나 받을 때마다 깜박입니다.

 

Micro 5Pin 연결

Windows에 USB UART 추가

Windows 장치 관리자에서 COM 포트가 추가 된 것을 확인 할 수 있습니다.

Serial Console 활성화

2가지 방법이 있으며 2가지 모두 결과는 /boot/config.txt 파일에 enable_uart=1 내용이 추가됩니다.

방법1. /boot/config.txt 파일 직접 수정

$ sudo vi /boot/config.txt

내용 추가

enable_uart=1

방법2. raspi-config 유틸리티 사용

raspi-config 실행

$ sudo raspi-config

[Interfacing Options] 선택

[Serial] 선택

[Yes] 버튼 선택

[Ok] 버튼 선택

[Finish] 버튼 선택

SSH 클라이언트 설정

SSH 이용 Raspberry Pi 연결

저작자 표시
신고

Raspberry Pi - VNC 서버 설치

OS/Raspberry Pi 2017.09.04 00:31 Posted by 파란크리스마스

출처 : Raspberry Pi 3를 VNC로 접속하여 원격 제어하는 방법 (x11vnc)

VNC 서버 설치

$ sudo apt-get install x11vnc xinetd

VNC 서버 해상도 설정

$ sudo vi /boot/config.txt

주석 제거

# uncomment to force a console size. By default it will be display's size minus
# overscan.
framebuffer_width=1280
framebuffer_height=720

재부팅

$ sudo shutdown -r now

암호 설정

$ sudo x11vnc -storepasswd /etc/x11vnc.pass
Enter VNC password: 
Verify password:    
Write password to /etc/x11vnc.pass?  [y]/n y
Password written to: /etc/x11vnc.pass

암호 설정

$ sudo vi /lib/systemd/system/x11vnc.service

주석 제거

[Unit]
Description="x11vnc"
Requires=display-manager.service
After=display-manager.service

[Service]
ExecStart=/usr/bin/x11vnc -xkb -loop -noxrecord -noxfixes -noxdamage -display :0 -auth guess -rfbauth /etc/x11vnc.pass
ExecStop=/usr/bin/killall x11vnc

[Install]
WantedBy=multi-user.target

VNC 서버 실행

$ sudo systemctl daemon-reload
$ sudo systemctl start x11vnc

VNC 서버 서비스 등록

$ sudo systemctl enable x11vnc
Created symlink from /etc/systemd/system/multi-user.target.wants/x11vnc.service to /lib/systemd/system/x11vnc.service.


저작자 표시
신고

Python - mjpeg 영상 화면에 출력

OS/Raspberry Pi 2017.08.16 00:15 Posted by 파란크리스마스

출처 : python - How to parse mjpeg http stream from ip camera? - Stack Overflow

Python - mjpeg 영상 화면에 출력

import cv2
import requests
import numpy as np

#stream = urllib.request.urlopen("http://127.0.0.1:8080/?action=snapshot")
#stream = urllib2.urlopen("http://127.0.0.1:8080/?action=snapshot")
#bytes = bytes()

while True:
    r = requests.get('http://127.0.0.1:8080/?action=snapshot"', auth=('user', 'password'), stream=True)
    if(r.status_code == 200):
        bytes = b''
        for chunk in r.iter_content(chunk_size=1024):
            bytes += chunk
            a = bytes.find(b'\xff\xd8')
            b = bytes.find(b'\xff\xd9')
            if a != -1 and b != -1:
                jpg = bytes[a:b+2]
                bytes = bytes[b+2:]
                i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
                cv2.imshow('i', i)
                if cv2.waitKey(1) == 27:
                    exit(0)
    else:
        print("Received unexpected status code {}".format(r.status_code))


저작자 표시
신고

Raspberry PI -무선랜카드 AP모드로 사용하기

OS/Raspberry Pi 2017.05.22 23:31 Posted by 파란크리스마스

Raspberry PI -무선랜카드 AP모드로 사용하기

출처 : Using your new Raspberry Pi 3 as a WiFi access point with hostapd
라즈베리파이 활용강좌 : 라즈베리파이를 무선공유기(AP)로 활용하기 |
SETTING UP A RASPBERRY PI AS AN ACCESS POINT IN A STANDALONE NETWORK

최신으로 업데이트

$ sudo apt-get update;sudo apt-get upgrade -y

AP 관련 패키지 설치

$ sudo apt-get install hostapd bridge-utils iw
$ sudo apt-get install dnsmasq

wlan0 고정 아이피 설정

$ sudo vi /etc/dhcpcd.conf

아래 내용 하단에 추가

denyinterfaces wlan0

Network 설정 파일 백업하고 수정

$ sudo cp /etc/network/interfaces /etc/network/interfaces.bak
$ sudo vi /etc/network/interfaces

# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet static
    address 192.168.0.1
    netmask 255.255.255.0
    network 192.168.1.0
    broadcast 192.168.0.255
#    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

wlan 다시 시작

$ sudo service dhcpcd restart
$ sudo ifdown wlan0
$ sudo ifup wlan0

DHCP 서버 설정

$ sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig
$ sudo vi /etc/dnsmasq.conf

interface=wlan0      # Use interface wlan0
listen-address=192.168.0.1 # Explicitly specify the address to listen on
bind-interfaces      # Bind to the interface to make sure we aren't sending things elsewhere
server=8.8.8.8       # Forward DNS requests to Google DNS
domain-needed        # Don't forward short names
bogus-priv           # Never forward addresses in the non-routed address spaces.
dhcp-range=192.168.0.2,192.168.0.20,255.255.255.0,24h # Assign IP addresses between 192.168.0.2 and 192.168.0.20 with a 24 hour lease time

hostapd.conf 파일 생성

$ sudo vi /etc/hostapd/hostapd.conf

# This is the name of the WiFi interface we configured above
interface=wlan0

# Use the nl80211 driver with the brcmfmac driver
driver=nl80211

# This is the name of the network
ssid=Pi3-AP

# Use the 2.4GHz band
hw_mode=g

# Use channel 6
channel=6

# Enable 802.11n
ieee80211n=1

# Enable WMM
wmm_enabled=1

# Enable 40MHz channels with 20ns guard interval
ht_capab=[HT40][SHORT-GI-20][DSSS_CCK-40]

# Accept all MAC addresses
macaddr_acl=0

# Use WPA authentication
auth_algs=1

# Require clients to know the network name
ignore_broadcast_ssid=0

# Use WPA2
wpa=2

# Use a pre-shared key
wpa_key_mgmt=WPA-PSK

# The network passphrase
wpa_passphrase=raspberry

# Use AES, instead of TKIP
rsn_pairwise=CCMP

default hostapd 파일 수정

$ sudo vi /etc/default/hostapd

DAEMON_CONF="/etc/hostapd/hostapd.conf"

서비스 다시 시작

$ sudo service hostapd start  
$ sudo service dnsmasq start
저작자 표시
신고

Raspberry PI - Speaker pHAT

OS/Raspberry Pi 2017.02.12 19:35 Posted by 파란크리스마스

Speaker pHAT

출처 : https://shop.pimoroni.com/products/speaker-phat
Setting up pHAT DAC
Pi VU Meter ( ALSA Plugin to display a VU meter on various Raspberry Pi add-ons )
Raspberry Pi Zero Streaming Airplay using Speaker pHAT - YouTube

자동 설치

$ curl https://get.pimoroni.com/phatdac | bash

Pi VU Meter 설치

출처 : Pi VU Meter ( ALSA Plugin to display a VU meter on various Raspberry Pi add-ons )

$ git clone https://github.com/pimoroni/pivumeter.git
$ cd pivumeter
$ setup.sh blinkt

수동 설치

$ git clone https://github.com/pimoroni/speaker-phat
Cloning into 'speaker-phat'...
remote: Counting objects: 128, done.
remote: Total 128 (delta 0), reused 0 (delta 0), pack-reused 128
Receiving objects: 100% (128/128), 114.17 KiB | 23.00 KiB/s, done.
Resolving deltas: 100% (39/39), done.
Checking connectivity... done.
$ cd speaker-phat
$ sudo ./setup.sh
 
This script will install everything needed to use
Speaker pHAT
 
--- Warning ---
 
Always be careful when running scripts and commands
copied from the internet. Ensure they are from a
trusted source.
 
Checking for required packages...
Enabling I2C interface...
 
Installing ALSA plugin...
 
Configuring sound output...
 
Adding Device Tree Entry to /boot/config.txt
dtoverlay=i2s-mmap
dtoverlay=hifiberry-dac
 
Commenting out Blacklist entry in
/etc/modprobe.d/raspi-blacklist.conf
 
Disabling default sound driver
 
All done!
 
Enjoy your Speaker pHAT!
 
Some changes made to your system require
your computer to reboot to take effect.
 
Would you like to reboot now? [y/N]
$ sudo shutdown -r now

플레이어 설치

출처 : GUI based MP3 players

$ apt-get install lxmusic


저작자 표시
신고

Raspberry Pi - USB 마이크 설치

OS/Raspberry Pi 2016.12.31 00:07 Posted by 파란크리스마스

USB에 설치된 디바이스목록 확인

출처 : Yong Choi's IT Blog: Raspberry Pi에서 소리 입력 및 녹음하기

$ lsusb
Bus 001 Device 006: ID 0d8c:013c C-Media Electronics, Inc. CM108 Audio Controller
Bus 001 Device 005: ID 148f:3070 Ralink Technology, Corp. RT2870/RT3070 Wireless Adapter
Bus 001 Device 004: ID 24ae:2000  
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp. 
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

USB 오디오 녹음장치 확인

$ arecord -l
**** List of CAPTURE Hardware Devices ****
card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

녹음

$ arecord -D plughw:1,0 -d 10 test.wav
Recording WAVE 'test.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono

재생

$ aplay test.wav 
Playing WAVE 'test.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono
저작자 표시
신고

Raspberry Pi - 스마트미러 설치

OS/Raspberry Pi 2016.12.30 19:41 Posted by 파란크리스마스

출처 : SPEECH TO TEXT(STT) 라이브러리와 프로세싱을 이용하여 음성인식 테스트하기
라즈베리파이에서 Node.js 사용하기 [ 1. Node.js 및 기타 모듈 설치 ]
라즈베리파이 Node.js 최신버전 설치 :: 생각 정리소
[라즈하이파이] Runeaudio를 이용한 오디오 시스템 만들기 | - 산딸기마을
Building TensorFlow for Raspberry Pi: a Step-By-Step Guide

스마트미러 자동설치

출처 : Smart Mirror Installation

$ curl -sL https://raw.githubusercontent.com/evancohen/smart-mirror/master/scripts/pi-install.sh | bash
 ________  _____ ______   ________  ________  _________         
|\   ____\|\   _ \  _   \|\   __  \|\   __  \|\___   ___\       
\ \  \___|\ \  \\\__\ \  \ \  \|\  \ \  \|\  \|___ \  \_|       
 \ \_____  \ \  \\|__| \  \ \   __  \ \   _  _\   \ \  \        
  \|____|\  \ \  \    \ \  \ \  \ \  \ \  \\  \|   \ \  \       
    ____\_\  \ \__\    \ \__\ \__\ \__\ \__\\ _\    \ \__\      
   |\_________\|__|     \|__|\|__|\|__|\|__|\|__|    \|__|      
   \|_________|                                                 
                                                                
 _____ ______   ___  ________  ________  ________  ________     
|\   _ \  _   \|\  \|\   __  \|\   __  \|\   __  \|\   __  \    
\ \  \\\__\ \  \ \  \ \  \|\  \ \  \|\  \ \  \|\  \ \  \|\  \   
 \ \  \\|__| \  \ \  \ \   _  _\ \   _  _\ \  \\\  \ \   _  _\  
  \ \  \    \ \  \ \  \ \  \\  \\ \  \\  \\ \  \\\  \ \  \\  \  
   \ \__\    \ \__\ \__\ \__\\ _\\ \__\\ _\\ \_______\ \__\\ _\ 
    \|__|     \|__|\|__|\|__|\|__|\|__|\|__|\|_______|\|__|\|__|
 
This script will install the smart-mirror and it's dependencies.
Please do not exit this script until it is complete.
 
Installing native dependencies

스마트미러 수동설치

출처 : Smart Mirror Install Raspbian

스마트미러 설치전 관련 라이브러리 설치

출처 : Install Smart Mirror dependencies

$ sudo apt-get install sox libatlas-base-dev

스마트미러 설치

출처 : Smart Mirror 스마트 미러 만들기- 4 Smart Mirror GitHub 다운 및 실행

$ git clone https://github.com/evancohen/smart-mirror.git
Cloning into 'smart-mirror'...
remote: Counting objects: 3760, done.
remote: Compressing objects: 100% (107/107), done.
remote: Total 3760 (delta 56), reused 0 (delta 0), pack-reused 3653
Receiving objects: 100% (3760/3760), 10.85 MiB | 2.09 MiB/s, done.
Resolving deltas: 100% (2072/2072), done.
Checking connectivity... done.
$ cd smart-mirror
$ cp config.default.json config.json
$ npm install

스마트미러 실행

$ npm start

스마트미러 실행 화면

한국어 음석 출력 테스트 - say함수 추가

<!-- responsivevoice.js -->
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<script>
function say() {
  if(responsiveVoice.voiceSupport()) {
    console.log('Responsvie Voice Supported');
    responsiveVoice.speak("예쁜 꽃 그리는 법","Korean Female");
  }
}
</script>

say함수 실행 버튼 추가

<button onclick="javascript:say();">Speak</button>

실행

$ cat .asoundrc 
pcm.!default {
        type asym
        playback.pcm
        {
                type hw
                card 0
        }
        capture.pcm
        {
                type plug
                slave.pcm "hw:1,0"
        }
}

ctl.!default {
        type hw
        card 0
}

오디오 환경 설정

pi@raspberrypi:~/smart-mirror$ scripts/conf-audio.sh



List of Capture Devices

0) card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]
Enter the number of the Capture device you would like to use:  
0



List of Playback Devices

0) card 0: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA]
1) card 0: ALSA [bcm2835 ALSA], device 1: bcm2835 ALSA [bcm2835 IEC958/HDMI]
Enter the number of the Playback device you would like to use:  
0



pcm.!default {
  type asym
   playback.pcm {
     type plug
     # card 0: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA][choice]
     slave.pcm "hw:0,0"
   }
   capture.pcm {
     type plug
     # card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio][choice]
     slave.pcm "hw:1,0"
   }
}



pi@raspberrypi:~/smart-mirror$ cat ~/.asoundrc
pcm.!default {
  type asym
   playback.pcm {
     type plug
     # card 0: ALSA [bcm2835 ALSA], device 0: bcm2835 ALSA [bcm2835 ALSA][choice]
     slave.pcm "hw:0,0"
   }
   capture.pcm {
     type plug
     # card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio][choice]
     slave.pcm "hw:1,0"
   }
}
pi@raspberrypi:~/smart-mirror$ 


hotword 확인

$ vi plugins/speech/service.js

            ipcRenderer.on('hotword', () => {
                console.log('hotword')
                callbacks.listening(true)
            })

부팅시 스마트미러 시작

출처 : Setting up Smart-Mirror to Run on Boot · Smart Mirror Documentation

실행 스크립트 작업 디렉토리에 복사

$ cd ~
$ cp ./smart-mirror/scripts/bash-start.sh smart-start.sh
$ chown pi:pi /home/pi/smart-start.sh
$ chmod +x /home/pi/smart-start.sh

pi 계정의 X-Windows가 실행시 실행되도록 실행 스크리트 등록

$ vi /home/pi/.config/lxsession/LXDE-pi/autostart

/home/pi/smart-start.sh &

snowboy 설치 (옵션)

출처 : https://github.com/kitt-ai/snowboy
ハンドメイド Alexa Festival! Serverless、IoT + Voice への誘い。ラズパイ + Alexa Voice Servce(Python)

$ sudo apt-get install swig3.0 python-pyaudio python3-pyaudio sox python-dev
$ pip install pyaudio
$ sudo apt-get install libmagic-dev libatlas-base-dev
$ sudo npm install -g node-pre-gyp
$ git clone https://github.com/Kitt-AI/snowboy.git
$ cd snowboy
$ npm install

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

-

모듈

node-record-lpcm16

smart-mirror/plugins/speech/service.js

            ipcRenderer.on('hotword', () => {
                console.log('hotword')
                callbacks.listening(true)
            })

smart-mirror/node_modules/sonus/index.js

'use strict'

const record = require('node-record-lpcm16')
const stream = require('stream')
const {Detector, Models} = require('snowboy')

const ERROR = {
  NOT_STARTED: "NOT_STARTED",
  INVALID_INDEX: "INVALID_INDEX"
}

const CloudSpeechRecognizer = {}
CloudSpeechRecognizer.init = recognizer => {
  const csr = new stream.Writable()
  csr.listening = false
  csr.recognizer = recognizer
  return csr
}

CloudSpeechRecognizer.startStreaming = (options, audioStream, cloudSpeechRecognizer) => {
  if (cloudSpeechRecognizer.listening) {
    return
  }

  cloudSpeechRecognizer.listening = true

  const recognizer = cloudSpeechRecognizer.recognizer
  const recognitionStream = recognizer.createRecognizeStream({
    config: {
      encoding: 'LINEAR16',
      sampleRate: 16000,
      languageCode: options.language
    },
    singleUtterance: true,
    interimResults: true,
    verbose: true
  })

  recognitionStream.on('error', err => cloudSpeechRecognizer.emit('error', err))


  recognitionStream.on('data', data => {
    if (data) {
      cloudSpeechRecognizer.emit('data', data)
      if (data.endpointerType === 'END_OF_UTTERANCE') {
        cloudSpeechRecognizer.listening = false
        audioStream.unpipe(recognitionStream)
      }
    }
  })

  audioStream.pipe(recognitionStream)
}

const Sonus = {}
Sonus.annyang = require('./lib/annyang-core.js')

Sonus.init = (options, recognizer) => {
  // don't mutate options
  const opts = Object.assign({}, options),
    models = new Models(),
    sonus = new stream.Writable(),
    csr = CloudSpeechRecognizer.init(recognizer)
  sonus.mic = {}
  sonus.recordProgram = opts.recordProgram
  sonus.started = false

  // If we don't have any hotwords passed in, add the default global model
  opts.hotwords = opts.hotwords || [1]
  opts.hotwords.forEach(model => {
    models.add({
      file: model.file || 'node_modules/snowboy/resources/snowboy.umdl',
      sensitivity: model.sensitivity || '0.5',
      hotwords: model.hotword || 'default'
    })
  })

  // defaults
  opts.models = models
  opts.resource = opts.resource || 'node_modules/snowboy/resources/common.res'
  opts.audioGain = opts.audioGain || 2.0
  opts.language = opts.language || 'en-US' //https://cloud.google.com/speech/docs/languages

  const detector = sonus.detector = new Detector(opts)

  detector.on('silence', () => sonus.emit('silence'))
  detector.on('sound', () => sonus.emit('sound'))

  // When a hotword is detected pipe the audio stream to speech detection
  detector.on('hotword', (index, hotword) => {
    sonus.trigger(index, hotword)
  })

  csr.on('error', error => sonus.emit('error', { streamingError: error }))

  let transcriptEmpty = true
  csr.on('data', data => {
    const result = data.results[0]
    if (result) {
      transcriptEmpty = false
      if (result.isFinal) {
        sonus.emit('final-result', result.transcript)
        Sonus.annyang.trigger(result.transcript)
        transcriptEmpty = true //reset transcript
      } else {
        sonus.emit('partial-result', result.transcript)
      }
    } else if (data.endpointerType === 'END_OF_UTTERANCE' && transcriptEmpty) {
      sonus.emit('final-result', "")
    }
  })

  sonus.trigger = (index, hotword) => {
    if (sonus.started) {
      try {
        let triggerHotword = (index == 0) ? hotword : models.lookup(index)
        sonus.emit('hotword', index, triggerHotword)
        CloudSpeechRecognizer.startStreaming(opts, sonus.mic, csr)
      } catch (e) {
        throw ERROR.INVALID_INDEX
      }
    } else {
      throw ERROR.NOT_STARTED
    }
  }

  return sonus
}

Sonus.start = sonus => {
  sonus.mic = record.start({
    threshold: 0,
    recordProgram: sonus.recordProgram || "rec",
    verbose: false
  })

  sonus.mic.pipe(sonus.detector)
  sonus.started = true
}

Sonus.trigger = (sonus, index, hotword) => sonus.trigger(index, hotword)

Sonus.pause = sonus => sonus.mic.pause()

Sonus.resume = sonus => sonus.mic.resume()

Sonus.stop = () => record.stop()

module.exports = Sonus

smart-mirror/app/js/controller.js

(function (angular) {
    'use strict';

    function MirrorCtrl(
        Focus,
        SpeechService,
        AutoSleepService,
        LightService,
        $rootScope, $scope, $timeout, $interval, tmhDynamicLocale, $translate) {

        // Local Scope Vars
        var _this = this;
        $scope.listening = false;
        $scope.debug = false;
        $scope.commands = [];
        $scope.partialResult = $translate.instant('home.commands');
        $scope.layoutName = 'main';
        $scope.config = config;

        // Set up our Focus
        $rootScope.$on('focus', function(targetScope, newFocus){
            $scope.focus = newFocus;
        })

        Focus.change("default");

        //set lang
        if (config.general.language.substr(0, 2) == 'en') {
            moment.locale(config.general.language,
                {
                    calendar: {
                        lastWeek: '[Last] dddd',
                        lastDay: '[Yesterday]',
                        sameDay: '[Today]',
                        nextDay: '[Tomorrow]',
                        nextWeek: 'dddd',
                        sameElse: 'L'
                    }
                }
            )
        } else {
                moment.locale(config.general.language)
        }
        //Initialize the speech service

        var resetCommandTimeout;
        SpeechService.init({
            listening: function (listening) {
                $scope.listening = listening;
                if (listening && !AutoSleepService.woke) {
                    AutoSleepService.wake()
                    $scope.focus = AutoSleepService.scope;
                }
            },
            partialResult: function (result) {
                $scope.partialResult = result;
                $timeout.cancel(resetCommandTimeout);
            },
            finalResult: function (result) {
                if (typeof result !== 'undefined') {
                    $scope.partialResult = result;
                    resetCommandTimeout = $timeout(restCommand, 5000);
                }
            },
            error: function (error) {
                console.log(error);
                if (error.error == "network") {
                    $scope.speechError = "Google Speech Recognizer: Network Error (Speech quota exceeded?)";
                }
            }
        });

        //Update the time
        function updateTime() {
            $scope.date = new moment();

            // Auto wake at a specific time
            if (typeof config.autoTimer !== 'undefined' && typeof config.autoTimer.autoWake !== 'undefined' && config.autoTimer.autoWake == moment().format('HH:mm:ss')) {
                console.debug('Auto-wake', config.autoTimer.autoWake);
                AutoSleepService.wake()
                $scope.focus = AutoSleepService.scope;
                AutoSleepService.startAutoSleepTimer();
            }
        }

        // Reset the command text
        var restCommand = function () {
            $translate('home.commands').then(function (translation) {
                $scope.partialResult = translation;
            });
        };

        _this.init = function () {
            AutoSleepService.startAutoSleepTimer();

            $interval(updateTime, 1000);
            updateTime();
            restCommand();

            var defaultView = function () {
                console.debug("Ok, going to default view...");
                Focus.change("default");
            }

            // List commands
            SpeechService.addCommand('list', function () {
                console.debug("Here is a list of commands...");
                console.log(SpeechService.commands);
                $scope.commands = SpeechService.getCommands();
                Focus.change("commands");
            });

            // Go back to default view
            SpeechService.addCommand('home', defaultView);

            SpeechService.addCommand('debug', function () {
                console.debug("Boop Boop. Showing debug info...");
                $scope.debug = true;
            });

            // Check the time
            SpeechService.addCommand('time_show', function () {
                console.debug("It is", moment().format('h:mm:ss a'));
            });

            // Control light
            SpeechService.addCommand('light_action', function (state, action) {
                LightService.performUpdate(state + " " + action);
            });
        };

        _this.init();
    }

    angular.module('SmartMirror')
        .controller('MirrorCtrl', MirrorCtrl);

    function themeController($scope) {
        $scope.layoutName = (typeof config.layout !== 'undefined' && config.layout) ? config.layout : 'main';
    }

    angular.module('SmartMirror')
        .controller('Theme', themeController);

} (window.angular));
저작자 표시
신고

Raspberry Pi - node.js 6.0.x 설치

OS/Raspberry Pi 2016.12.30 19:24 Posted by 파란크리스마스

기존 설치된 node.js 제거 (옵션)

출처 : Installing Node.js v4.0.0 on a Raspberry Pi (All Models) - Blog - Wia

$ sudo apt-get remove --purge nodejs
$ sudo apt-get autoremove

node.js 설치

출처 : Install Raspbian

$ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
$ sudo apt-get install -y nodejs

node.js 수동 설치(zero의 경우)

출처 : Raspberry Pi에 Node-JS 설치하기 - MY - LIFE - Tistory

$ wget https://nodejs.org/dist/v6.9.4/node-v6.9.4-linux-armv6l.tar.gz
$ tar -xvf node-v6.9.4-linux-armv6l.tar.gz
$ sudo mv node-v6.9.4-linux-armv6l /opt

node.js 경로 추가

$ sudo vi /etc/profile

export NODE=/opt/node-v6.9.4-linux-armv6l
export NODE_PATH=$NODE/lib/node_modules
export PATH=$PATH:$NODE/bin:$NODE_PATH

node.js 설치 확인

$ command node -v
v6.9.4
저작자 표시
신고

Raspberry Pi - node.js v4.0 설치

OS/Raspberry Pi 2016.12.18 12:35 Posted by 파란크리스마스

출처 : 라즈베리파이에서 Node.js 사용하기 [ 1. Node.js 및 기타 모듈 설치 ]
라즈베리파이 Node.js 최신버전 설치 :: 생각 정리소
[라즈하이파이] Runeaudio를 이용한 오디오 시스템 만들기 | - 산딸기마을

라즈베리파이 업데이트

$ sudo rpi-update
$ sync
$ sudo reboot

node.js 제거 (방법1)

출처 : 라즈베리파이 Node.js 최신버전 설치 :: 생각 정리소

$ sudo apt-get remove nodered -y
$ sudo apt-get remove nodejs nodejs-legacy -y
$ sudo apt-get remove npm -y

기존 설치된 node.js 제거

출처 : Installing Node.js v4.0.0 on a Raspberry Pi (All Models) - Blog - Wia

$ sudo apt-get remove --purge nodejs

node.js 설치

출처 : Raspberry Pi에 Node-JS 설치하기 - MY - LIFE - Tistory

$ wget https://nodejs.org/dist/v4.0.0/node-v4.0.0-linux-armv7l.tar.gz
$ tar -xvf node-v4.0.0-linux-armv7l.tar.gz
$ sudo mv node-v4.0.0-linux-armv7l /opt

node.js 경로 추가

$ sudo vi /etc/profile

NODE=/opt/node-v4.0.0-linux-armv7l
NODE_PATH=$NODE/lib/node_modules
PATH=$PATH:$NODE/bin:$NODE_PATH

node.js 설치 확인

$ command node -v
v4.0.0
저작자 표시
신고

Blueinno2(RFduinoBLE) - Raspberry PI 3 / BLE 연동

OS/Raspberry Pi 2016.12.14 01:11 Posted by 파란크리스마스

출처 : Raspberry Pi: Control WS2812B (NeoPixels) With Bluetooth LE
Eclipse Kura™ Documentation
The Pi4J Project

Bluetooth 모듈이 내장된 블루이노2로 BLE 송신하고, 라즈베리파이3의 Bluetooth 모듈로 수신 받아 데이터처리 해보았습니다.

블루이노2 코드

#include <RFduinoBLE.h>

int Potent=2;
boolean is_connect;

void setup() {
  // put your setup code here, to run once:
  RFduinoBLE.deviceName = "bluexmas";

  // this is the data we want to appear in the advertisement
  //RFduinoBLE.advertisementData = "My BLE LED";
  
  //RFduinoBLE.advertisementInterval = MILLISECONDS(300);
  //RFduinoBLE.txPowerLevel = -20;  // (-20dbM to +4 dBm)
    
  Serial.begin(9600);  
  Serial.println("Start Test");      // With more than 15 characters thie Start Test keeps happening

  // start the BLE stack
  RFduinoBLE.begin();  
}

void loop() {
  char BPM_lcd[10];
  
  RFduino_ULPDelay(100);  
  // Switch to lower power mode
  //RFduino_ULPDelay(INFINITE);
  //RFduino_ULPDelay( SECONDS(1) ); //sample once per second

  if (is_connect) {
    int sensorValue = analogRead(Potent);
    Serial.println(sensorValue);             // debug value

    //sprintf(BPM_lcd, "%10d", sensorValue);
    //lcd.println(BPM_lcd);     
    
    RFduinoBLE.sendInt(sensorValue);  //sends the char array
  }
}

void RFduinoBLE_onConnect() {
  // Debug message printed to Serial interface
  Serial.println("RFduino connected");
  is_connect = true;
}

void RFduinoBLE_onDisconnect() { 
  // Debug message printed to Serial interface
  Serial.println("RFduino disconnected");
  is_connect = false;
}

void RFduinoBLE_onReceive(char *data, int len) {
  // Debug message printed to Serial interface
  Serial.println("Data received: ");
  for(int i=0;i<len;i++)
    Serial.print(data[i]);
    Serial.println();
    Serial.println(data);
}

Blueinno.java

BLE 관련 코드만 보기 편하게 하기 위해서 모터 제어 관련 코드는 빼고 블루이노2와 통신하는 부분만 공개

package ble.blueinno2;

import java.util.List;
import java.util.Scanner;

import org.eclipse.kura.KuraException;
import org.eclipse.kura.bluetooth.BluetoothDevice;
import org.eclipse.kura.bluetooth.BluetoothGatt;
import org.eclipse.kura.bluetooth.BluetoothGattService;
import org.eclipse.kura.bluetooth.BluetoothLeNotificationListener;
import org.eclipse.kura.bluetooth.BluetoothLeScanListener;
import org.eclipse.kura.linux.bluetooth.util.BluetoothProcess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Blueinno implements BluetoothLeNotificationListener, BluetoothLeScanListener {
	
	private static final Logger logger = LoggerFactory.getLogger(BluetoothProcess.class);

	private BluetoothGatt m_bluetoothGatt;
	private BluetoothDevice m_device;
	private boolean m_connected;

	public Blueinno(BluetoothDevice bluetoothDevice) {
		// m_device = bluetoothDevice;
		m_connected = false;
	}

	public BluetoothDevice getBluetoothDevice() {
		return m_device;
	}

	public void setBluetoothDevice(BluetoothDevice device) {
		m_device = device;
	}

	public boolean isConnected() {
		return m_connected;
	}

	public boolean connect(BluetoothLeNotificationListener listener) throws KuraException {
		m_bluetoothGatt = m_device.getBluetoothGatt();
		logger.info("접속시도");
		boolean connected = m_bluetoothGatt.connect();
		if (connected) {
			m_bluetoothGatt.setBluetoothLeNotificationListener(listener);
			logger.info("리스너등록");
			m_connected = true;
			return true;
		} else {
			// If connect command is not executed, close gatttool
			m_bluetoothGatt.disconnect();
			m_connected = false;
			return false;
		}
	}

	public void disconnect() {
		if (m_bluetoothGatt != null) {
			m_bluetoothGatt.disconnect();
			m_connected = false;
		}
	}

	/*
	 * Discover services
	 */
	public List<BluetoothGattService> discoverServices() {
		return m_bluetoothGatt.getServices();
	}

	@Override
	public void onScanFailed(int errorCode) {
		// TODO Auto-generated method stub
		System.out.println("error = " + errorCode);
	}

	@Override
	public void onScanResults(List<BluetoothDevice> devices) {
		logger.info("onScanResults = " + devices.size());

		for (BluetoothDevice device : devices) {
			logger.info("Found Bluetooth Device " + device.getName() + " [" + device.getAdress() + "]");
		}
		
		System.out.print("ble address > ");
		Scanner scanner = new Scanner(System.in);
		String blc_address = scanner.next();
		
		BluetoothDevice nurum_device = null;
		for (BluetoothDevice device : devices) {
			if (device.getAdress().equals(blc_address)) {
				nurum_device = device;
			}
		}
		
		if (nurum_device != null) {
			//ble_nurum = new Blueinno(nurum_device);
			this.setBluetoothDevice(nurum_device);
			try {
				if (this.connect(this)) {
					System.out.println("ble connect");
					
					Runnable aa = new Runnable() {
						
						@Override
						public void run() {
							while (true) {
								try {
									String sensorValue = m_bluetoothGatt.readCharacteristicValue("0x000e");
									System.out.println(sensorValue);
									
									// 모터제어
									// 생략
								} catch (KuraException e1) {
									e1.printStackTrace();
								}
								try {
									Thread.sleep(100);
								} catch (Exception e) {
									
								}
							}
						}
					};
					
					Thread bb = new Thread(aa);
					bb.start();
				}
			} catch (KuraException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void onDataReceived(String handle, String value) {
		System.out.println("handle: " + handle + " value: " + value);
	}
}

BlueinnoMain.java

package ble.blueinno2;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.eclipse.kura.linux.bluetooth.le.BluetoothLeScanner;

public class BlueinnoMain {
	
	Logger logger = Logger.getLogger(this.getClass());

	private Blueinno blueinno = null;
	
	public static void main(String[] args) throws Exception {
		BlueinnoMain bletest = new BlueinnoMain();
		bletest.init();
		bletest.startScan();
	}
	
	public void init() {
		Logger.getRootLogger().setLevel(Level.DEBUG);
		logger.info("초기화");
		blueinno = new Blueinno();
	}

	public void startScan() throws InterruptedException {
		BluetoothLeScanner m_bls = new BluetoothLeScanner();
		m_bls.startScan("hci0", blueinno);
		Thread.sleep(10000);
		m_bls.killScan();
	}
}

실행


저작자 표시
신고

Raspberry Pi & Bluetooth LE(nurum) / LED Control

OS/Raspberry Pi 2016.11.20 02:11 Posted by 파란크리스마스

출처 : Eclipse Kura™ Documentation
The Pi4J Project

라즈베리파이2에 BLE 동글이와 BLE 스마트 버튼인 nurum으로 클릭 이벤트를 받아서
GPIO를 이용해서 LED를 컨트롤 해보았습니다.

BleNurum class

package bletest;

import java.util.List;

import org.eclipse.kura.KuraException;
import org.eclipse.kura.bluetooth.BluetoothDevice;
import org.eclipse.kura.bluetooth.BluetoothGatt;
import org.eclipse.kura.bluetooth.BluetoothGattService;
import org.eclipse.kura.bluetooth.BluetoothLeNotificationListener;

public class BleNurum {

	private BluetoothGatt m_bluetoothGatt;
	private BluetoothDevice m_device;
	private boolean m_connected;

	public BleNurum(BluetoothDevice bluetoothDevice) {
		m_device = bluetoothDevice;
		m_connected = false;
	}

	public BluetoothDevice getBluetoothDevice() {
		return m_device;
	}

	public void setBluetoothDevice(BluetoothDevice device) {
		m_device = device;
	}

	public boolean isConnected() {
		return m_connected;
	}

	public boolean connect(BluetoothLeNotificationListener listener) throws KuraException {
		m_bluetoothGatt = m_device.getBluetoothGatt();
		boolean connected = m_bluetoothGatt.connect();
		if (connected) {
			m_bluetoothGatt.setBluetoothLeNotificationListener(listener);
			m_connected = true;
			return true;
		} else {
			// If connect command is not executed, close gatttool
			m_bluetoothGatt.disconnect();
			m_connected = false;
			return false;
		}
	}

	public void disconnect() {
		if (m_bluetoothGatt != null) {
			m_bluetoothGatt.disconnect();
			m_connected = false;
		}
	}

	/*
	 * Discover services
	 */
	public List<BluetoothGattService> discoverServices() {
		return m_bluetoothGatt.getServices();
	}
}

BleTestMain class

package bletest;

import java.nio.ByteBuffer;
import java.util.List;
import java.util.Scanner;

import org.eclipse.kura.KuraException;
import org.eclipse.kura.bluetooth.BluetoothDevice;
import org.eclipse.kura.bluetooth.BluetoothLeNotificationListener;
import org.eclipse.kura.bluetooth.BluetoothLeScanListener;
import org.eclipse.kura.linux.bluetooth.le.BluetoothLeScanner;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;

public class BleTestMain implements BluetoothLeScanListener, BluetoothLeNotificationListener {
	
	private BleNurum ble_nurum = null;
	private GpioController gpio = null;
	private GpioPinDigitalOutput led_01 = null;
	private GpioPinDigitalOutput led_02 = null;
	
	public static void main(String[] args) throws Exception {
		BleTestMain bletest = new BleTestMain();
		bletest.init();
		bletest.startScan();
	}
	
	public void init() {
		// create gpio controller
		gpio = GpioFactory.getInstance();
		led_01 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_08, "Red LED", PinState.HIGH);
		led_02 = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_09, "Blue LED", PinState.HIGH);
		// set shutdown state for this pin
		led_01.setShutdownOptions(true, PinState.LOW);
		led_02.setShutdownOptions(true, PinState.LOW);
		led_01.low();
		led_02.low();
	}

	public void startScan() throws InterruptedException {
		BluetoothLeScanner m_bls = new BluetoothLeScanner();
		m_bls.startScan("hci0", this);

		Thread.sleep(3000);

		m_bls.killScan();
	}

	@Override
	public void onScanFailed(int errorCode) {
		// TODO Auto-generated method stub
		System.out.println("error = " + errorCode);
	}

	@Override
	public void onScanResults(List<BluetoothDevice> devices) {
		System.out.println("onScanResults = " + devices.size());

		for (BluetoothDevice device : devices) {
			System.out.println("Found Bluetooth Device " + device.getName() + " [" + device.getAdress() + "]");
		}
		
		System.out.print("ble address > ");
		Scanner scanner = new Scanner(System.in);
		String blc_address = scanner.next();
		
		BluetoothDevice nurum_device = null;
		for (BluetoothDevice device : devices) {
			if (device.getAdress().equals(blc_address)) {
				nurum_device = device;
			}
		}
		
		if (nurum_device != null) {
			ble_nurum = new BleNurum(nurum_device);
			try {
				if (ble_nurum.connect(this)) {
					System.out.println("ble connect");
				}
			} catch (KuraException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static byte[] decode(String hex) {

		String[] list = hex.split("(?<=\\G.{2})");
		ByteBuffer buffer = ByteBuffer.allocate(list.length);
		System.out.println(list.length);
		for (String str : list)
			buffer.put(Byte.parseByte(str, 16));

		return buffer.array();

	}

	@Override
	public void onDataReceived(String handle, String value) {
		String val = new String( decode(value.replaceAll("\\p{Z}", "")) );
		
		System.out.println("handle: " + handle + " value: " + value + " / " + val);
		
		if (val.equals("!1")) {
			led_01.toggle();
		}
		
		if (val.equals("!2")) {
			led_02.toggle();
		}
		
		if (val.equals("!3")) {
			led_01.low();
			led_02.low();
		}		
		
		if (val.equals("!H")) {
			ble_nurum.disconnect();
			gpio.shutdown();
			System.exit(1);
		}
	}
}

실행

$ sudo java -cp .:pi4j-core.jar:org.apache.commons.io_2.4.0.jar:org.eclipse.equinox.io_1.0.400.v20120522-2049.jar:org.eclipse.osgi_3.8.1.v20120830-144521.jar:org.eclipse.osgi.services_3.3.100.v20120522-1822.jar:org.eclipse.osgi.util_3.2.300.v20120522-1822.jar:org.eclipse.soda.dk.comm_1.2.1.jar:slf4j.api_1.6.4.jar:slf4j.jdk14_1.6.4.jar:slf4j.log4j12_1.6.0.jar:usb4java-javax_1.0.0.jar bletest.BleTestMain

저작자 표시
신고

Raspberry PI Pixel

OS/Raspberry Pi 2016.10.12 14:27 Posted by 파란크리스마스

마우스 반응 속도 개선

출처 : 라즈베리파이 무선마우스 속도 감도 문제 해결

cmdline.txt 파일의 첫줄에 usbhid.mousepoll=0 추가 / 디폴트가 8로 너무 빠르다 싶으면 숫자를 올려준다.

$ sudo vi /boot/cmdline.txt

최신 버전으로 업데이트

$ sudo apt-get update
$ sudo apt-get upgrade

XRDP 사용

출처 : Introducing PIXEL - Raspberry Pi
Raspberry Pi Adds Beautiful "Pixel" Desktop Environment To ...

최신 라즈베리파이OS인 PIXEL의 경우 기본적으로 VNC서버가 설치되어 있으므로, XRDP를 사용하실 경우 VNC 서버를 삭제 해야됩니다.

VNC서버 삭제 (RealVNC가 설치되어 있는 경우 사용)

$ sudo apt-get autoremove --purge realvnc
$ sudo apt-get purge realvnc-vnc-server

XRDP 설치

$ sudo apt-get install xrdp

라즈베리파이 펌웨어 업데이트

출처 : 라즈베리파이 펌웨어 업데이트 하기 (firmware update on the R-Pi)

$ sudo apt-get install ca-certificates
Reading package lists... Done
Building dependency tree       
Reading state information... Done
ca-certificates is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
$ sudo apt-get install git-core
Reading package lists... Done
Building dependency tree       
Reading state information... Done
git-core is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

리눅스 정보

$ uname -a
Linux raspberrypi 4.4.21-v7+ #911 SMP Thu Sep 15 14:22:38 BST 2016 armv7l GNU/Linux

HC-06 UART 설정

출처 : Raspberry Pi 3 UART baud rate workaround
RaspberryPi3でシリアル通信を行う - Qiita
Brian Dorey.com | Raspberry Pi 3 UART Boot Overlay Part Two

환경파일 /boot/config.txt 수정

내용 추가 dtoverlay=pi3-miniuart-bt, enable_uart=1, core_freq=25

$ sudo vi /boot/config.txt

변경후

# Uncomment this to enable the lirc-rpi module
#dtoverlay=lirc-rpi
dtoverlay=pi3-miniuart-bt
enable_uart=1
core_freq=250

해상도 변경

출처 : studymake.blogspot.kr: [00076] 라즈베리파이 해상도 변경하는 방법

$ sudo vi /boot/config.txt

아래 해당 부분의 주석 제거

hdmi_force_hotplug = 1
hdmi_group = 2
hdmi_mode = 16 # 16 = 1024x768   60 Hz
hdmi_drive = 1

한글 폰트 설치

$ sudo apt-get install ttf-unfonts-core

한글 입력기 설치

$ sudo apt-get install fcitx-hangul

node.js 설치

출처 : Installing Node.js v4.0.0 on a Raspberry Pi (All Models) - Blog - Wia

$ wget https://nodejs.org/dist/v4.0.0/node-v4.0.0-linux-armv7l.tar.gz
$ tar -xvf node-v4.0.0-linux-armv7l.tar.gz
$ cd node-v4.0.0-linux-armv7l
$ sudo cp -R * /usr/local/

node.js 설치 확인

$ command node -v
v4.0.0

스마트미러 설치

출처 : Smart Mirror 스마트 미러 만들기- 4 Smart Mirror GitHub 다운 및 실행

$ mkdir test-smart-mirror
$ cd test-smart-mirror
$ git clone https://github.com/evancohen/smart-mirror.git
Cloning into 'smart-mirror'...
remote: Counting objects: 3760, done.
remote: Compressing objects: 100% (107/107), done.
remote: Total 3760 (delta 56), reused 0 (delta 0), pack-reused 3653
Receiving objects: 100% (3760/3760), 10.85 MiB | 2.09 MiB/s, done.
Resolving deltas: 100% (2072/2072), done.
Checking connectivity... done.
$ cd smart-mirror
$ cp config.example.js config.js
$ npm install

스마트미러 실행

$ npm start

스마트미러 실행 화면


$ lsusb
Bus 001 Device 004: ID 148f:3070 Ralink Technology, Corp. RT2870/RT3070 Wireless Adapter
Bus 001 Device 006: ID 0d8c:013c C-Media Electronics, Inc. CM108 Audio Controller
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp. 
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub


$ arecord -l
**** List of CAPTURE Hardware Devices ****
card 1: Device [USB PnP Sound Device], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0


저작자 표시
신고


 

티스토리 툴바