将python脚本转换为php以获取dht22传感器数据读取

时间:2015-04-05 08:09:18

标签: php python

我会将此Python代码转换为在php中读取DHT22传感器数据。我不懂python所以我无法转换php中的所有函数。

python脚本来自here(我添加了numpy库,因为没有它我是一个错误)

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

import socket
import numpy

TCP_ADDR = 'MYIP'
TCP_PORT = 8899

PACK_LEN = 11

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.settimeout(30)

s.connect((TCP_ADDR, TCP_PORT))

bytes_data = numpy.zeros(PACK_LEN,int)

str_data = s.recv(PACK_LEN) #this should probably have a timeout
hex_data = str_data.encode('hex')

for n in range(0,PACK_LEN): #convert to array of bytes
    lower = 2*n
    upper = lower + 2
    bytes_data[n] = int(hex_data[lower:upper],16)


humid =  (((bytes_data[6])<<8)+(bytes_data[7]))/10.0
temp =  (((((bytes_data[8])&0x7F)<<8)+(bytes_data[9]))/10.0)

if int(bytes_data[8]) & 0x80: #invert temp if sign bit is set
    temp = -1.0* temp

checksum = (int(sum(bytes_data[0:10])) & 0xFF)+1

if checksum == bytes_data[10]:
    print "T" + str(temp) + " H" + str(humid)
else:
    print "Invalid. :("

1 个答案:

答案 0 :(得分:0)

这只是php中的测试

$fp = fsockopen("192.168.0.12", 8899, $errno, $errstr, 20);

if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {

    fwrite($fp, "\n");
    $code = fread($fp, 26);
    fclose($fp);

    $code = array_shift( unpack('H*', $code) );
    echo $code;
}