204_Raspi_水分センサ_(last code)

水分センサのpythonコード(2ファイル)をそのまま。。。


①水分センサの測定用、ADCを介したpython

(adafruit_mcp3008_3.py)

————————————-

#!/usr/bin/env python
# -*- coding: utf-8 -*

# Written by Limor “Ladyada” Fried for Adafruit Industries, (c) 2015
# This code is released into the public domain
# import module
import time
import os
import RPi.GPIO as GPIO

import random # モジュールのインポート

# ドライバをimport
import mysql.connector

if __name__ == ‘__main__’:
# データベースに接続

# localhost access ok!!!!!
connect = mysql.connector.connect(user=’root’, password=’root’, host=’localhost’, database=’moisture_sensor’, charset=’utf8′)

cursor = connect.cursor()

# temp=random.randint(0, 50)
# humid=random.randint(0, 100)
GPIO.setmode(GPIO.BCM)
DEBUG = 1

# read SPI data from MCP3008 chip, 8 possible adc’s (0 thru 7)
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 7) or (adcnum < 0)):
return -1
GPIO.output(cspin, True)

GPIO.output(clockpin, False)  # start clock low
GPIO.output(cspin, False)     # bring CS low

commandout = adcnum
commandout |= 0x18  # start bit + single-ended bit
commandout <<= 3    # we only need to send 5 bits here
for i in range(5):
if (commandout & 0x80):
GPIO.output(mosipin, True)
else:
GPIO.output(mosipin, False)
commandout <<= 1
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)

adcout = 0
# read in one empty bit, one null bit and 10 ADC bits
for i in range(12):
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout <<= 1
if (GPIO.input(misopin)):
adcout |= 0x1

GPIO.output(cspin, True)

adcout >>= 1       # first bit is ‘null’ so drop it
return adcout

# change these as desired – they’re the pins connected from the
# SPI port on the ADC to the Cobbler
SPICLK = 18
SPIMISO = 23
SPIMOSI = 24
SPICS = 25
# set up the SPI interface pins
GPIO.setup(SPIMOSI, GPIO.OUT)
GPIO.setup(SPIMISO, GPIO.IN)
GPIO.setup(SPICLK, GPIO.OUT)
GPIO.setup(SPICS, GPIO.OUT)

# 10k trim pot connected to adc #0
potentiometer_adc = 0;

last_read = 0       # this keeps track of the last potentiometer value
tolerance = 5       # to keep from being jittery we’ll only change
# volume when the pot has moved more than 5 ‘counts’

n=1
#while n<=1:

if (n == 1):
# we’ll assume that the pot didn’t move
trim_pot_changed = False

# read the analog pin
trim_pot = readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
# how much has it changed since the last read?
pot_adjust = abs(trim_pot – last_read)

if DEBUG:
print “trim_pot:”, trim_pot
print “pot_adjust:”, pot_adjust
print “last_read”, last_read

if ( pot_adjust > tolerance ):
trim_pot_changed = True

if DEBUG:
print “trim_pot_changed”, trim_pot_changed

if ( trim_pot_changed ):
set_volume = trim_pot / 10.24           # convert 10bit adc0 (0-1024) trim pot read into 0-100 volume level
set_volume = round(set_volume)          # round out decimal value
set_volume = int(set_volume)            # cast volume as integer

print ‘Volume = {volume}%’ .format(volume = set_volume)
set_vol_cmd = ‘sudo amixer cset numid=1 — {volume}% > /dev/null’ .format(volume = set_volume)
os.system(set_vol_cmd)  # set volume

if DEBUG:
print “set_volume”, set_volume
print “tri_pot_changed”, set_volume

# save the potentiometer reading for the next loop
last_read = trim_pot
# insert

cursor.execute(‘insert into ms_tbl(time_stamp,adc,read_adc,volts,comment,trim_pot,pot_adjust,last_read,trim_pot_changed,set_volume) values (now(),%s ,%s, %s, %s, %s, %s, %s, %s, %s)’, (trim_pot,set_volume,’taniku_pot2017/03/25′,’comment2017/03/25′,trim_pot,pot_adjust,last_read,trim_pot_changed,set_volume))
# Delete
cursor.execute(‘DELETE FROM ms_tbl ORDER BY Num ASC LIMIT 1’)

# autocommitではないので、明示的にコミットする
connect.commit()

# データベースから切断
cursor.close()
connect.close()
# hang out and do nothing for a half second
# time.sleep(0.10)


②RaspiのデータをさくらVPSへ転送、pythonコード

(20170323_snd_skr_ms1.py)

————————————-

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# import module
import os
import random # モジュールのインポート
# ドライバをimport
import mysql.connector
if __name__ == ‘__main__’:
# データベースに接続
# localhost access ok!!!!!
connect = mysql.connector.connect(user=’root’, password=’root’, host=’localhost’, database=’moisture_sensor’, charset=’utf8′)
cursor = connect.cursor()
# select
cursor.execute(‘select * from ms_tbl order by Num DESC limit 1′)
rows = cursor.fetchall()
# 出力
for i in rows:
print(“—send below data to sakravps success !!—-“)
print(i[0])
print(i[1])
print(i[2])
print(i[3])
print(i[4])
print(i[5])
print(i[6])
print(i[7])
print(i[8])
print(i[9])
print(i[10])

# sakuravps access
connect = mysql.connector.connect(user=’raspai’, password=’Aa123456′, host=’160.16.50.187′, database=’20170301_moisture_sensor’, charset=’utf8′)
cursor = connect.cursor()

# insert
cursor.execute(‘insert into ms_tbl(time_stamp,adc,read_adc,volts,comment,trim_pot,pot_adjust,last_read,trim_pot_changed,set_volume) values (%s, %s, %s, %s, %s, %s, %s, %s ,%s, %s)’, (i[1],i[2],i[3],i[4],i[5],i[6],i[7],i[8],i[9],i[10]))
# cursor.execute(‘insert into ms_tbl(time_stamp,adc,read_adc,volts,comment) values (%s, %s, %s, %s, %s)’, (i[1],i[2],i[3],i[4],i[5]))

# Delete
cursor.execute(‘DELETE FROM ms_tbl ORDER BY Num ASC LIMIT 1’)
# autocommitではないので、明示的にコミットする
connect.commit()
# データベースから切断
cursor.close()
connect.close()


以上

203_Raspi_温度センサ+水分センサ_1台集約

Raspiの一号機に「温度センサ+水分センサ」を集約しました。

 

■Before、それぞれで測定中。。。

 

水分センサ。。。

 

温度センサ。。。。(湿度計は復活しなかった・・・)

 

■After 合体!1台で両方を計測中。。。。

まあ、問題ないかな??

ちょっと、Raspiの負荷が心配ですが。。。。

以上

 

202_水分センサ_グラフMySQLのdataそのもの表示

一応、さくらVPSのMySQLデータを確認するためのphpコードも。

置き場所は、

/var/www/html/mois_gra

コードは、下記

ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー

?php
//MySQLに接続し、データベースを選択します。
mysql_select_db(‘20170301_moisture_sensor’) or die(mysql_error());

//SQLクエリを実行します。
//SQLクエリを実行します。(カウント追加2016/12/30)
$res1 = mysql_query(‘SELECT count(*) from ms_tbl ‘) or die(mysql_error());
//結果を出力します。
while ($row1 = mysql_fetch_array($res1, MYSQL_NUM)){
echo “vpsのms_tbl件数は、<br />\n”;
echo $row1[0].”\t”;
echo “<br />件です。<br />\n”;
echo “——————\n<br>”;
}
while ($row = mysql_fetch_array($res, MYSQL_NUM)){
echo $row[0].”\t”;
echo $row[1].”\t”;
echo $row[2].”\n”;
echo $row[3].”\n”;
echo $row[4].”\n”;
echo $row[5].”\n”;
echo $row[6].”\t”;
echo $row[7].”\n”;
echo $row[8].”\n”;
echo $row[9].”\n”;
echo $row[10].”\n”;
echo “<br />\n”;
echo “——————\n<br>”;
}
//結果セットを開放し、接続を閉じます。
mysql_free_result($res);
mysql_close($conn);
?>

201_水分センサ_グラフWebコード

さくらVPSでグラフ表のWebコードです。

置き場所は、

/var/www/html/mois_gra

コードは、下記

————————————

    <!– AJAX API のロード –>
    // グラフ作成用のコールバック関数
    function drawChart() {
    // データテーブルの作成
    var data = google.visualization.arrayToDataTable([
       mysql_select_db(‘20170301_moisture_sensor’) or die(mysql_error());
       //SQLクエリを実行します。
      //$drawScript ='<br>グラフデーターを書くまでの記述<br>’;
       $i = 0;
       while ($row = mysql_fetch_array($res, MYSQL_NUM)){
       if ($i != 0) {
       } else {
       }
        print $drawScript;
        //結果セットを開放し、接続を閉じます。
        mysql_free_result($res);
        mysql_close($conn);
       ?>
   ]);
    // グラフのオプションを設定
    var options = {
        title: ‘moisture_sensor用グラフ’
    };
    // LineChart のオブジェクトの作成
    // データテーブルとオプションを渡して、グラフを描画
    chart.draw(data, options);
    }
    </script>
  </head>
  <body>
    <!– グラフを描く div 要素 –>
    <div id=”chart_div” style=”width: 80%; height: 400px;”></div>
     参考値<br>
    —————————-<br>
     肉葉植物     470-490 , 47-49<br>
    —————————-<br>
     胡蝶蘭(小) 437-? , 43-? <br>
    —————————-<br>
     ゴムの木     389-? , 38-? <br>
    —————————-<br>
    <br>
    表示データ<br>
    *****************************<br>
    [Num, time_stamp, adc, read_adc, volts, comment ] <br>
   <?php
    //MySQLに接続し、データベースを選択します。
    mysql_select_db(‘20170301_moisture_sensor’) or die(mysql_error());
    //SQLクエリを実行します。
    //結果を出力します。
    while ($row = mysql_fetch_array($res, MYSQL_NUM)){
    echo “[\n”;
    echo $row[0].”\n”;
    echo “,\n'”;
    echo $row[1].”\t”;
    echo “‘,\n”;
    echo $row[2].”\n”;
    echo “,\n”;
    echo $row[3].”\n”;
    echo “,\n”;
    echo $row[4].”\n”;
    echo “,\n”;
    echo $row[5].”\n”;
    echo “],\n”;
    echo “<br />\n”;
    }
    //結果セットを開放し、接続を閉じます。
    mysql_free_result($res);
    mysql_close($conn);
   ?>
    *****************************<br>
  </body>
</html>

200_水分センサ_sampleコードそのもの(勉強)

adafruit_mcp3008.py
====================
#!/usr/bin/env python

# Written by Limor “Ladyada” Fried for Adafruit Industries, (c) 2015
# This code is released into the public domain

import time
import os
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
DEBUG = 1

# read SPI data from MCP3008 chip, 8 possible adc’s (0 thru 7)
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 7) or (adcnum < 0)):
return -1
GPIO.output(cspin, True)

GPIO.output(clockpin, False)  # start clock low
GPIO.output(cspin, False)     # bring CS low

commandout = adcnum
commandout |= 0x18  # start bit + single-ended bit
commandout <<= 3    # we only need to send 5 bits here
for i in range(5):
if (commandout & 0x80):
GPIO.output(mosipin, True)
else:
GPIO.output(mosipin, False)
commandout <<= 1
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)

adcout = 0
# read in one empty bit, one null bit and 10 ADC bits
for i in range(12):
GPIO.output(clockpin, True)
GPIO.output(clockpin, False)
adcout <<= 1
if (GPIO.input(misopin)):
adcout |= 0x1

GPIO.output(cspin, True)

adcout >>= 1       # first bit is ‘null’ so drop it
return adcout

# change these as desired – they’re the pins connected from the
# SPI port on the ADC to the Cobbler
SPICLK = 18
SPIMISO = 23
SPIMOSI = 24
SPICS = 25
# set up the SPI interface pins
GPIO.setup(SPIMOSI, GPIO.OUT)
GPIO.setup(SPIMISO, GPIO.IN)
GPIO.setup(SPICLK, GPIO.OUT)
GPIO.setup(SPICS, GPIO.OUT)

# 10k trim pot connected to adc #0
potentiometer_adc = 0;

last_read = 0       # this keeps track of the last potentiometer value
tolerance = 5       # to keep from being jittery we’ll only change
# volume when the pot has moved more than 5 ‘counts’

while True:
# we’ll assume that the pot didn’t move
trim_pot_changed = False

# read the analog pin
trim_pot = readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
# how much has it changed since the last read?
pot_adjust = abs(trim_pot – last_read)

if DEBUG:
print “trim_pot:”, trim_pot
print “pot_adjust:”, pot_adjust
print “last_read”, last_read

if ( pot_adjust > tolerance ):
trim_pot_changed = True

if DEBUG:
print “trim_pot_changed”, trim_pot_changed

if ( trim_pot_changed ):
set_volume = trim_pot / 10.24           # convert 10bit adc0 (0-1024) trim pot read into 0-100 volume level
set_volume = round(set_volume)          # round out decimal value
set_volume = int(set_volume)            # cast volume as integer

print ‘Volume = {volume}%’ .format(volume = set_volume)
set_vol_cmd = ‘sudo amixer cset numid=1 — {volume}% > /dev/null’ .format(volume = set_volume)
os.system(set_vol_cmd)  # set volume

if DEBUG:
print “set_volume”, set_volume
print “tri_pot_changed”, set_volume

# save the potentiometer reading for the next loop
last_read = trim_pot

# hang out and do nothing for a half second
time.sleep(0.5)
====================

 

199_水分センサ_sampleコードで試し

いよいよ水分センサ。

コードはそのまま使います。(まずは準備)

————————-

Python sample code getting from Web
 
$ git clone git://gist.github.com/3151375.git
 
you find new directory “3151375”
In i tyou find python sample code “adafruit_mcp3008.py”
 
I will use this code itself.
 
 
 
before that, I need set up other package and so on.
 
 
Necessary Packages
$ sudo apt-get update
$ sudo apt-get install python-dev
 
Next, Install the latest RPi.GPIO module. We will use easy_install to manage the python packages.
 
$ sudo apt-get install python-setuptools
$ sudo easy_install rpi.gpio
 
 
Connect between RaspberryPi and this mousture curcuit.
Let’s get started!
 
$ cd 3151375
$ sudo python adafruit_mcp3008.py

————————-

結果は、

(1)taniku-pot-mad   355
(2)ko-cyou-ran case 422
(3)water case       501
(4)dry case           0
(5)shida-tree case  152

測定周期やMySQL保存はこの次に。

はたして・・・

まずは、配線完了!!

(1)まずは、多肉植物、から。。

  

=============
taniku-pot-mad case 
————-
pi@raspberrypi20170226:~/3151375 $ sudo python adafruit_mcp3008.py
adafruit_mcp3008.py:56: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPIMOSI, GPIO.OUT)
adafruit_mcp3008.py:58: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPICLK, GPIO.OUT)
adafruit_mcp3008.py:59: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPICS, GPIO.OUT)
trim_pot: 349
pot_adjust: 349
last_read 0
trim_pot_changed True
Volume = 34%
set_volume 34
tri_pot_changed 34
trim_pot: 356
pot_adjust: 7
last_read 349
trim_pot_changed True
Volume = 35%
set_volume 35
tri_pot_changed 35
trim_pot: 354
pot_adjust: 2
last_read 356
trim_pot_changed False
trim_pot: 355
pot_adjust: 1
last_read 356
trim_pot_changed False
trim_pot: 356
pot_adjust: 0
last_read 356
trim_pot_changed False
trim_pot: 356
pot_adjust: 0
last_read 356
trim_pot_changed False
trim_pot: 356
pot_adjust: 0
last_read 356
trim_pot_changed False
trim_pot: 354
pot_adjust: 2
last_read 356
trim_pot_changed False
^CTraceback (most recent call last):
  File “adafruit_mcp3008.py”, line 105, in <module>
    time.sleep(0.5)
KeyboardInterrupt

(2)次は、胡蝶蘭

=============
ko-cyou-ran case 
————-
pi@raspberrypi20170226:~/3151375 $ sudo python adafruit_mcp3008.py
adafruit_mcp3008.py:56: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPIMOSI, GPIO.OUT)
adafruit_mcp3008.py:58: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPICLK, GPIO.OUT)
adafruit_mcp3008.py:59: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPICS, GPIO.OUT)
trim_pot: 422
pot_adjust: 422
last_read 0
trim_pot_changed True
Volume = 41%
set_volume 41
tri_pot_changed 41
trim_pot: 427
pot_adjust: 5
last_read 422
trim_pot_changed False
trim_pot: 425
pot_adjust: 3
last_read 422
trim_pot_changed False
trim_pot: 424
pot_adjust: 2
last_read 422
trim_pot_changed False
trim_pot: 424
pot_adjust: 2
last_read 422
trim_pot_changed False
trim_pot: 424
pot_adjust: 2
last_read 422
trim_pot_changed False
trim_pot: 425
pot_adjust: 3
last_read 422
trim_pot_changed False
trim_pot: 426
pot_adjust: 4
last_read 422
trim_pot_changed False
^CTraceback (most recent call last):
  File “adafruit_mcp3008.py”, line 105, in <module>
    time.sleep(0.5)
KeyboardInterrupt

 

(3)次は、水だけ(水100%)

=============
water case 
————-
pi@raspberrypi20170226:~/3151375 $ sudo python adafruit_mcp3008.py
adafruit_mcp3008.py:56: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPIMOSI, GPIO.OUT)
adafruit_mcp3008.py:58: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPICLK, GPIO.OUT)
adafruit_mcp3008.py:59: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPICS, GPIO.OUT)
trim_pot: 501
pot_adjust: 501
last_read 0
trim_pot_changed True
Volume = 49%
set_volume 49
tri_pot_changed 49
trim_pot: 501
pot_adjust: 0
last_read 501
trim_pot_changed False
trim_pot: 503
pot_adjust: 2
last_read 501
trim_pot_changed False
trim_pot: 503
pot_adjust: 2
last_read 501
trim_pot_changed False
trim_pot: 503
pot_adjust: 2
last_read 501
trim_pot_changed False
trim_pot: 504
pot_adjust: 3
last_read 501
trim_pot_changed False
trim_pot: 501
pot_adjust: 0
last_read 501
trim_pot_changed False
^CTraceback (most recent call last):
  File “adafruit_mcp3008.py”, line 105, in <module>
    time.sleep(0.5)
KeyboardInterrupt

(4)まったく挿さないのは。。。

=============
dry case 
————-
pi@raspberrypi20170226:~/3151375 $ sudo python adafruit_mcp3008.py
adafruit_mcp3008.py:56: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPIMOSI, GPIO.OUT)
adafruit_mcp3008.py:58: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPICLK, GPIO.OUT)
adafruit_mcp3008.py:59: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPICS, GPIO.OUT)
trim_pot: 0
pot_adjust: 0
last_read 0
trim_pot_changed False
trim_pot: 0
pot_adjust: 0
last_read 0
trim_pot_changed False
trim_pot: 0
pot_adjust: 0
last_read 0
trim_pot_changed False
trim_pot: 0
pot_adjust: 0
last_read 0
trim_pot_changed False
trim_pot: 0
pot_adjust: 0
last_read 0
trim_pot_changed False
trim_pot: 0
pot_adjust: 0
last_read 0
trim_pot_changed False
trim_pot: 0
pot_adjust: 0
last_read 0
trim_pot_changed False
trim_pot: 0
pot_adjust: 0
last_read 0
trim_pot_changed False
trim_pot: 0
pot_adjust: 0
last_read 0
trim_pot_changed False
^CTraceback (most recent call last):
  File “adafruit_mcp3008.py”, line 105, in <module>
    time.sleep(0.5)
KeyboardInterrupt

(5)シダ植物は・・・

=============
shida-tree case 
————-
pi@raspberrypi20170226:~/3151375 $ sudo python adafruit_mcp3008.py
adafruit_mcp3008.py:56: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPIMOSI, GPIO.OUT)
adafruit_mcp3008.py:58: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPICLK, GPIO.OUT)
adafruit_mcp3008.py:59: RuntimeWarning: This channel is already in use, continuing anyway.  Use GPIO.setwarnings(False) to disable warnings.
  GPIO.setup(SPICS, GPIO.OUT)
trim_pot: 150
pot_adjust: 150
last_read 0
trim_pot_changed True
Volume = 15%
set_volume 15
tri_pot_changed 15
trim_pot: 151
pot_adjust: 1
last_read 150
trim_pot_changed False
trim_pot: 156
pot_adjust: 6
last_read 150
trim_pot_changed True
Volume = 15%
set_volume 15
tri_pot_changed 15
trim_pot: 154
pot_adjust: 2
last_read 156
trim_pot_changed False
trim_pot: 151
pot_adjust: 5
last_read 156
trim_pot_changed False
trim_pot: 154
pot_adjust: 2
last_read 156
trim_pot_changed False
trim_pot: 152
pot_adjust: 4
last_read 156
trim_pot_changed False
^CTraceback (most recent call last):
  File “adafruit_mcp3008.py”, line 105, in <module>
    time.sleep(0.5)
KeyboardInterrupt

以上、  さあ、次はカスタマイズ・・・・・・

 

198_水分センサ_半田ごて

さあ、半田ごてです。久しぶり。。。

 

完成品チェック!

 

側面A、、まあまあかな???

 

側面B、うーーーーん、まあままかな???

 

まあ、、動けばいいよね???

 

以上

197_php_photo (Google Cloud Vision API完成!)その4

■PHPでGoogle Cloud Vision APIにリクエスト
ここからは、サンプルプログラムにいきなり。
ズルく行きます。
参考は下記。
「Google Cloud Vision API(画像解析)を30分で試す」
http://qiita.com/t-fujiwara/items/7e1f7c52a73887519ac1
このサンプルをそのまま借りてまず動くか?やってみます。
=======================
<?php
// APIキー
$api_key = “AIzaSyCKmmfDVoUhjGLyKaTBwTPncIbXd87VGWc” ;
        // 画像へのパス
$argv[1]=
$image_path = “$argv[1]” ;
        // リクエスト用のJSONを作成
$json = json_encode( array(
“requests” => array(
array(
“image” => array(
“content” => base64_encode( file_get_contents( $image_path ) ) ,
) ,
“features” => array(
array(
“type” => “SAFE_SEARCH_DETECTION” ,
“maxResults” => 3 ,
) ,
) ,
) ,
) ,
) ) ;
        // リクエストを実行
$curl = curl_init() ;
curl_setopt( $curl, CURLOPT_URL, “https://vision.googleapis.com/v1/images:annotate?key=*****************************************************************” . $api_key ) ;
curl_setopt( $curl, CURLOPT_HEADER, true ) ;
curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, “POST” ) ;
curl_setopt( $curl, CURLOPT_HTTPHEADER, array( “Content-Type: application/json” ) ) ;
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, false ) ;
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true ) ;
if( isset($referer) && !empty($referer) ) curl_setopt( $curl, CURLOPT_REFERER, $referer ) ;
curl_setopt( $curl, CURLOPT_TIMEOUT, 15 ) ;
curl_setopt( $curl, CURLOPT_POSTFIELDS, $json ) ;
$res1 = curl_exec( $curl ) ;
$res2 = curl_getinfo( $curl ) ;
curl_close( $curl ) ;
        // 取得したデータ
$json = substr( $res1, $res2[“header_size”] ) ;                         // 取得したJSON
$header = substr( $res1, 0, $res2[“header_size”] ) ;            // レスポンスヘッダー
        // 出力
echo “■出力結果” ;
echo $argv[1] ;
echo $json ;
=======================
はい、、ダメでした。。悲。。。。
なので、まず「ファイル指定」し、「ブラウザの制限」は無し、でやってみます。
phpファイル名は、「20170319_test1.php」
画像は、「富士山真上から」

コードは、下記
=======================
<?php
$path = ‘/home/dasudasu/www/php_photo_20170318/files/IMG_0323.JPG’;
$result = curl_init();
// curl url
curl_setopt($result, CURLOPT_URL, “https://vision.googleapis.com/v1/images:annotate?key=********************************************************”);
// post
curl_setopt($result, CURLOPT_CUSTOMREQUEST, ‘POST’);
// –data-binary
curl_setopt($result, CURLOPT_BINARYTRANSFER, true);
// header
curl_setopt($result, CURLOPT_HTTPHEADER, array( “Content-Type: application/json” ));
// get response with text
curl_setopt($result, CURLOPT_RETURNTRANSFER, true);
// image file
$file_contents = base64_encode(file_get_contents($path));
$request = ‘{
“requests”: [
{
“image”: {
“content”: “‘. $file_contents .'”
},
“features”: [
{
“type”: “LABEL_DETECTION”
}
]
}
]
}’;
curl_setopt($result, CURLOPT_POSTFIELDS, $request);
// result
$response = curl_exec($result);
//結果表示
echo “</br>”;
echo $response ;
=======================
で、結果は、
{ “responses”: [ { “labelAnnotations”: [ { “mid”: “/m/01bqvp”, “description”: “sky”, “score”: 0.97879976 }, { “mid”: “/g/11jxkqbpp”, “description”: “mountainous landforms”, “score”: 0.9590976 }, { “mid”: “/m/0csby”, “description”: “cloud”, “score”: 0.9397293 }, { “mid”: “/m/0csh5”, “description”: “cumulus”, “score”: 0.92631036 }, { “mid”: “/m/01l56l”, “description”: “landform”, “score”: 0.90823483 } ] } ] }
おおおお???、「mountain」「sky」とか出てる?
(図1)
では、つなげてみるか。。。
=======================
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>sample</title>
</head>
<body>
<p><?php
if (is_uploaded_file($_FILES[“upfile”][“tmp_name”])) {
if (move_uploaded_file($_FILES[“upfile”][“tmp_name”], “files/” . $_FILES[“upfile”][“name”])) {
chmod(“files/” . $_FILES[“upfile”][“name”], 0644);
echo $_FILES[“upfile”][“name”] . ” をアップロードしました。</br>”;
echo $_FILES[“upfile”][“type”] . ” は、画像のMIMETYPEです。</br>”;
echo $_FILES[“upfile”][“tmp_name”] . ” は、サーバのフルパスです。</br>”;
echo $_FILES[“upfile”][“error”] . ” は、エラーコードです(=正常:0)。</br>”;
echo $_FILES[“upfile”][“size”] . ” は、画像のサイズです(bite)。</br>”;
    echo ‘<br />’;
   //(1)このphpファイルのフルパス
echo “(1)このphpファイルのフルパス</br>”;
echo __FILE__ . ‘<br />’;
echo “</br>”;
   //(2)このphpファイルのディレクトリパス
echo “(2)このphpファイルのディレクトリパス</br>”;
echo dirname(__FILE__) . ‘<br />’;
echo “</br>”;
   //(3)このphpファイルのスクリプト名
echo “(3)このphpファイルのスクリプト名</br>”;
echo basename(__FILE__) . ‘<br />’;
echo “</br>”;
   //(4)ローカルパス名、・・・でも表示不可能、残念
echo ‘(4)ローカルパス名、・・・でも表示不可能、残念<br />’;
echo $_POST[“filepath”]. ‘<br />’;
echo “</br>”;
   //(5)サーバ保管フォルダのフルパス名・・OK!
echo ‘(5)サーバ保管フォルダのフルパス名<br />’;
echo dirname(__FILE__) . “/files/” .$_FILES[“upfile”][“name”] . ” は、サーバ保管フォルダのフルパスです。</br>”;
echo “</br>”;
   //(6)$argv[1]に合体させて表示、次phpにつなげる
echo ‘(6)$argv[1]に合体させて表示、次phpにつなげる<br />’;
$argv[1] = dirname(__FILE__) . “/files/” .$_FILES[“upfile”][“name”] ;
echo $argv[1];
  }
} else {
echo “ファイルが選択されていません。”;
}
$path = $argv[1];
$result = curl_init();
// curl url
curl_setopt($result, CURLOPT_URL, “https://vision.googleapis.com/v1/images:annotate?key=**********************************************************”);
// post
curl_setopt($result, CURLOPT_CUSTOMREQUEST, ‘POST’);
// –data-binary
curl_setopt($result, CURLOPT_BINARYTRANSFER, true);
// header
curl_setopt($result, CURLOPT_HTTPHEADER, array( “Content-Type: application/json” ));
// get response with text
curl_setopt($result, CURLOPT_RETURNTRANSFER, true);
// image file
$file_contents = base64_encode(file_get_contents($path));
$request = ‘{
“requests”: [
{
“image”: {
“content”: “‘. $file_contents .'”
},
“features”: [
{
“type”: “LABEL_DETECTION”
}
]
}
]
}’;
curl_setopt($result, CURLOPT_POSTFIELDS, $request);
// result
$response = curl_exec($result);
//結果表示
echo “</br>”;
echo “———————————-“;
echo “</br>”;
echo $response ;
echo “</br>”;
echo “———————————-“;
echo “</br>”;
?></p>
</body>
</html>
=======================
結果は、(ペンギンの画像だけど。。。)
いい感じかな???bird、、、とかって言ってるので。。。
(図2)
これが、転送した図
(図3)
まあ、良い経験できた、、と。
使いすぎないように注意!!!
以上

196_php_photo (Google Cloud Vision API準備)その3

■GoogleCloudVisionを使う
では、続き!
やはり勉強のためいささかの費用は出しても一度やってみよう!
で、cloud vison APIの手続きにはいります。
(図1)
課金が必要と言われる。。。行きましょう!
請求先アカウントを作成する必要があります。。。と。
(図2)
無料トライアルの同意書を読んで。。
(図3)
ようこそ、と。請求は確認までされないようなので一安心。
(図4)
Google Cloud Visionを有効化します。
画面が変わる。。
(図5)
認証情報の作成。。以前のは使えないみたい。。。
(図6)
使用するAPIに「Cloud Vision API」を、Google App Engine か Google Compute Engineを使用しましか?は、私もは「いいえ」を選択しました。
(図7)
役割は参考情報かな?アカウントを適当につけて、JSONを選ぶ。。
(図8)
アカウントの秘密鍵が作成されたらしい。。。
(図9)
DLもできた、、と。これ大切に保管!!と。
(図10)
これで Google Cloud Vision API の前準備が整いました、、と。
■APIキーの作成
次にGoogle Cloud Vision APIをWebから使うようにする為のAPIを発行します。。。と。
まずは、プロジェクトのトップ画面にアクセスして左上のバーガーマークをクリック。
メニューの一覧が表示されるので「API Manager」をクリックします。
(図11)
認証情報ページに遷移したら青いボタンの「認証情報を作成」をクリック。
クリックしたら表示される「API キー」をクリック。
「AIzaSyCKmmfDVoUhjGLyKaTBwTPncIbXd87VGWc」がAPIキーと。
(図12)
認証情報を入力します。
名前には同じくkey。受付URLは「*.dasudasu.sakura.ne.jp/*」とし、リクエスト元のURLをワイルドカード(アスタリスク)を使って設定しました。
(図13)
APIが出来上がりました。
これで、準備OKかな。。
(図14)
以上

195_php_photo (Google Cloud Vision APIを勉強)その2

PHPでのデータ受信
フォームから送信されたデータを受け取るPHPプログラムを作成、、か。。
アップロードされたファイルの情報は $_FILES に格納。。。と。
前に挙げたサンプルフォームからファイルを受け取る場合、form.html と同じフォルダに 20170318_upload.php (form の action で指定したファイル。)を作成し、以下の内容を記述します。。。と。
コードは、
=============
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>sample</title>
</head>
<body>
<p><?php
if (is_uploaded_file($_FILES[“upfile”][“tmp_name”])) {
if (move_uploaded_file($_FILES[“upfile”][“tmp_name”], “files/” . $_FILES[“upfile”][“name”])) {
chmod(“files/” . $_FILES[“upfile”][“name”], 0644);
echo $_FILES[“upfile”][“name”] . “をアップロードしました。”;
} else {
echo “ファイルをアップロードできません。”;
}
} else {
echo “ファイルが選択されていません。”;
}
?></p>
</body>
</html>
=============
同じ場所に files フォルダを作成し、書き込み権限を与えておきます、、、か。
でも、共用サーバはプロパティを編集するだけ!簡単だワ!
(図1)
さて、これで、、
「これで form.html に http:// でアクセスし、アップロードボタンを押すと files フォルダ内にファイルがアップロードされます。」、、か。
やってみよ!
はたして、、、?
(図2)
おお、、、入っとる!!
(図3)

以上