728x90

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

VNC 서버 설치

X
user@localhost:~

[user@localhost]$ sudo apt-get install x11vnc xinetd

VNC 서버 해상도 설정

X
user@localhost:~

[user@localhost]$ 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

재부팅

X
user@localhost:~

[user@localhost]$ sudo shutdown -r now

암호 설정

X
user@localhost:~

[user@localhost]$ 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

암호 설정

X
user@localhost:~

[user@localhost]$ 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 서버 실행

X
user@localhost:~

[user@localhost]$ sudo systemctl daemon-reload
[user@localhost]$ sudo systemctl start x11vnc

VNC 서버 서비스 등록

X
user@localhost:~

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


728x90
728x90

출처 : 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))


728x90
728x90

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

최신으로 업데이트

X
user@localhost:~

[user@localhost]$ sudo apt-get update;sudo apt-get upgrade -y

AP 관련 패키지 설치

X
user@localhost:~

[user@localhost]$ sudo apt-get install hostapd bridge-utils iw
[user@localhost]$ sudo apt-get install dnsmasq

wlan0 고정 아이피 설정

X
user@localhost:~

[user@localhost]$ sudo vi /etc/dhcpcd.conf

아래 내용 하단에 추가

denyinterfaces wlan0

Network 설정 파일 백업하고 수정

X
user@localhost:~

[user@localhost]$ sudo cp /etc/network/interfaces /etc/network/interfaces.bak
[user@localhost]$ 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 다시 시작

X
user@localhost:~

[user@localhost]$ sudo service dhcpcd restart
[user@localhost]$ sudo ifdown wlan0
[user@localhost]$ sudo ifup wlan0

DHCP 서버 설정

X
user@localhost:~

[user@localhost]$ sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig
[user@localhost]$ 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 파일 생성

X
user@localhost:~

[user@localhost]$ 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 파일 수정

X
user@localhost:~

[user@localhost]$ sudo vi /etc/default/hostapd


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

서비스 다시 시작

X
user@localhost:~

[user@localhost]$ sudo service hostapd start
[user@localhost]$ sudo service dnsmasq start

728x90
728x90

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

자동 설치

X
user@localhost:~

[user@localhost]$ 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 )

X
user@localhost:~

[user@localhost]$ git clone https://github.com/pimoroni/pivumeter.git
[user@localhost]$ cd pivumeter
[user@localhost]$ setup.sh blinkt

수동 설치

X
user@localhost:~

[user@localhost]$ 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.
[user@localhost]$ cd speaker-phat
[user@localhost]$ 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]
[user@localhost]$ sudo shutdown -r now

플레이어 설치

출처 : GUI based MP3 players

X
user@localhost:~

[user@localhost]$ apt-get install lxmusic


728x90
728x90

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

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

X
user@localhost:~

[user@localhost]$ 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 오디오 녹음장치 확인

X
user@localhost:~

[user@localhost]$ 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

녹음

X
user@localhost:~

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

재생

X
user@localhost:~

[user@localhost]$ aplay test.wav
Playing WAVE 'test.wav' : Unsigned 8 bit, Rate 8000 Hz, Mono

728x90
728x90

출처 : 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

X
user@localhost:~

[user@localhost]$ 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

X
user@localhost:~

[user@localhost]$ sudo apt-get install sox libatlas-base-dev

스마트미러 설치

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

X
user@localhost:~

[user@localhost]$ 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.
[user@localhost]$ cd smart-mirror
[user@localhost]$ cp config.default.json config.json
[user@localhost]$ npm install

스마트미러 실행

X
user@localhost:~

[user@localhost]$ 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>

실행

X
user@localhost:~

[user@localhost]$ 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 확인

X
user@localhost:~

[user@localhost]$ 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

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

X
user@localhost:~

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

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

X
user@localhost:~

[user@localhost]$ 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)

X
user@localhost:~

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




날씨가 출력 되지 않는 오류

출처 : 스마트미러 forecast 오류해결방법(GeolocationService 문제) - 징징이 : 네이버 블로그

날씨를 표시 못하는 문제가 발생했다. 

두가지 문제로 첫 번째는 위치 정보를 못 받아 오는 문제인데, 구글에 브라우져를 통해서 위치 정보를 받아 오는 함수가 될때가 있고, 안 될때가 있는데, 위치 정보를 수동으로 설정하는 방법으로 해결이 되지만, 

두 번째 문제로 날씨 정보 서비스가 한글을 지원하지 못하는 문제가 있어 영어(en) 으로 고정해야 날씨 정보를 조회 한다.

위치정보 수동 설정

plugins\weather\controller.js 내용수정

아래와 같이 소스를 영어로 고정하면 날씨 정보를 조회 한다.

	weather.get = function () {
		var weather_url = 'https://api.darksky.net/forecast/' + config.forecast.key + '/' +
            geoposition.coords.latitude + ',' + geoposition.coords.longitude + '?units=' +
            //config.forecast.units + "&lang=" + language + "&callback=JSON_CALLBACK";
            config.forecast.units + "&lang=en" + "&callback=JSON_CALLBACK";
		console.log(weather_url);
		return $http.jsonp(weather_url).then(function (response) {
			return weather.forecast = response;
		});
	};

위치정보 조회 서비스 호출 부분 (참고용)

위치정보 조회 서비스가 성공하면 interval 함수 호출로 주기적으로 날씨 정보를 조회 한다.

	GeolocationService.getLocation({ enableHighAccuracy: true }).then(function (geopo) {
		geoposition = geopo;
		refreshWeatherData(geoposition);
		$interval(refreshWeatherData, config.forecast.refreshInterval * 60000 || 7200000)
	});

-

-

-

-

-

-

-

-

-

-

모듈

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


728x90
728x90

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

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

X
user@localhost:~

[user@localhost]$ sudo apt-get remove --purge nodejs
[user@localhost]$ sudo apt-get autoremove

node.js 설치

출처 : Install Raspbian

X
user@localhost:~

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

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

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

X
user@localhost:~

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

node.js 경로 추가

X
user@localhost:~

[user@localhost]$ 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 설치 확인

X
user@localhost:~

[user@localhost]$ command node -v
v6.9.4

728x90
728x90

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

라즈베리파이 업데이트

X
user@localhost:~

[user@localhost]$ sudo rpi-update
[user@localhost]$ sync
[user@localhost]$ sudo reboot

node.js 제거 (방법1)

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

X
user@localhost:~

[user@localhost]$ sudo apt-get remove nodered -y
[user@localhost]$ sudo apt-get remove nodejs nodejs-legacy -y
[user@localhost]$ sudo apt-get remove npm -y

기존 설치된 node.js 제거

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

X
user@localhost:~

[user@localhost]$ sudo apt-get remove --purge nodejs

node.js 설치

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

X
user@localhost:~

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

node.js 경로 추가

X
user@localhost:~

[user@localhost]$ 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 설치 확인

X
user@localhost:~

[user@localhost]$ command node -v
v4.0.0

728x90

+ Recent posts