Convert python script to php for dht22 sensor data reading - php

I would convert this Python code to read DHT22 sensor data in php. I don't know python so I can't convert all functions in the php corrispondent.
The python script is from here (I add numpy library because I was an error without it)
#!/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. :("

It was just a test in 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;
}

Related

How do i send a byte stream to a socket with PHP?

In GO i can do the following:
conn, _ := net.Dial("tcp", CONNECT) // Client
request := []byte{01, 00} // The request start with 0100
request = append(request, []byte(`09302020073014323720200730007402`)...) // The request
conn.Write(request)
This does work, however, i'm unable to translate this to PHP.
What i have so far:
$fp = stream_socket_client("tcp://x:x", $errno, $errstr, 5);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$queryString = '010009302020073014323720200730007402';
fwrite($fp, $queryString);
echo fgets($fp, $responseSize);
fclose($fp);
}
I tried using the described solutions here with no success, the server does not recognise my input.
In your Go example, your request begins with the bytes 0x01, and 0x00. In PHP, you're writing the byte encoding of the string '0100'. These aren't exactly the same, and you can view how they differ here: https://play.golang.org/p/0gidDZe4lZF
What you really want to be writing is the single byte 0x0, and 0x1 at the beginning of your string instead of these characters.
Using PHP's builtin chr function we can create a string using the single bytes 0x0 and 0x1 like so:
$queryString = chr(0) . chr(1);
$queryString .= '09302020073014323720200730007402'
Barring any additional encoding issues on the PHP side of things, that should match your query in your Go example.

PHP - TCP/IP fsockopen

I was wondering if anyone has had any experience with this before. I'm trying to write a simple script that will continously read data from the TCP/IP stream but for some reason or another the script reads in a bunch of data, writes it out and then just stops.
$fp = fsockopen("xxxx", 3000, $errno, $errstr, 5);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
while (!feof($fp)) {
echo fgets($fp, 128)."\n";
fflush($fp);
}
fclose($fp);
}
I'd like it to have a constant flow to it, rather then echo out a bunch of data then wait 30 seconds and output a bunch more data. Anyone have any ideas?
---- EDIT ----
ZMQ Code
include 'zmsg.php';
$context = new ZMQContext();
$client = new ZMQSocket($context, ZMQ::SOCKET_DEALER);
// Generate printable identity for the client
$identity = sprintf ("%04X", rand(0, 0x10000));
$client->setSockOpt(ZMQ::SOCKOPT_IDENTITY, $identity);
$client->connect("tcp://xxxx:3000");
$read = $write = array();
$poll = new ZMQPoll();
$poll->add($client, ZMQ::POLL_IN);
$request_nbr = 0;
while (true) {
// Tick once per second, pulling in arriving messages
for ($centitick = 0; $centitick < 100; $centitick++) {
$events = $poll->poll($read, $write, 1000);
$zmsg = new Zmsg($client);
if ($events) {
$zmsg->recv();
echo $zmsg->body()."\n";
//printf ("%s: %s%s", $identity, $zmsg->body(), PHP_EOL);
}
}
$zmsg = new Zmsg($client);
//$zmsg->body_fmt("request #%d", ++$request_nbr)->send();
}
Here is how you connect to a server (as a client) if your goal is ONLY to PULL data (read).
<?php
$context = new ZMQContext();
$sock = new ZMQSocket($context, ZMQ::SOCKET_PULL);
$sock->connect("tcp://ADDRESS:3000");
while (true)
{
$request = $sock->recv(); # recv is blocking by default, no need to put timers.
printf ("Received: %s;%s", $request, PHP_EOL);
}
?>
if you want to reply, you'll need to use a pair socket (ZMQ::SOCKET_PAIR), then you can use:
$sock->send("data to send");
Also, if instead of you connecting to clients, clients connects to you, use the bind method instead of connect.
EDIT: use the PUSH socket type on the other side if you use the pull here, else, use the pair socket on both sides.

Getting domain information from url using PHP/Python

How can I get information about a domain name (such as owner or server details) using PHP or Python code? I'd like to avoid using any 3rd party web site.
Is this possible?
You can base yourself on the following whois script: http://www.phpeasycode.com/whois/
Here's an online demo.
The script first checks for the right whois server and then opens a socket on port 43. Here's a simpliefied query function based on the code from the demo above.
Each TLD has its own whois server. You can find a complete list here : http://www.iana.org/domains/root/db/ and http://www.whois365.com/en/listtld/
<?php
$whoisserver = "whois.pir.org";
$domain = "example.org";
$port = 43;
$timeout = 10;
$fp = #fsockopen($whoisserver, $port, $errno, $errstr, $timeout) or die("Socket Error " . $errno . " - " . $errstr);
fputs($fp, $domain . "\r\n");
$out = "";
while(!feof($fp)){
$out .= fgets($fp);
}
fclose($fp);
$res = "";
if((strpos(strtolower($out), "error") === FALSE) && (strpos(strtolower($out), "not allocated") === FALSE)) {
$rows = explode("\n", $out);
foreach($rows as $row) {
$row = trim($row);
if(($row != '') && ($row{0} != '#') && ($row{0} != '%')) {
$res .= $row."\n";
}
}
}
print $res;
First make your live easier:
pip install python-whois
pip install requests
Then do something like:
>>> import requests
>>> import urlparse
>>> import whois
>>> url = 'http://docs.python.org/3/'
>>> requests.head(url).headers['server']
'Apache/2.2.22 (Debian)'
>>> hostname = urlparse.urlparse(url).netloc
>>> print whois.whois(hostname)
creation_date: 1995-03-27 05:00:00
domain_name: PYTHON.ORG
emails: ['e89d6901ba3e470e8cedc3eaa32a0074-1697561#contact.gandi.net', 'e89d6901ba3e470e8cedc3eaa32a0074-1697561#contact.gandi.net', 'infrastructure-staff#python.org']
expiration_date: []
name_servers: ['NS3.P11.DYNECT.NET', 'NS1.P11.DYNECT.NET', 'NS2.P11.DYNECT.NET', 'NS4.P11.DYNECT.NET', '', '', '', '', '', '', '', '', '']
referral_url:
registrar: Gandi SAS (R42-LROR)
status: clientTransferProhibited
updated_date: 2013-08-15 00:20:19
whois_server:
>>>
actually, the previus answer now is wrong, urlparse change to urllib.parse, so it will be :
import requests
import urllib.parse
import whois
url = 'http://docs.python.org/3/'
requests.head(url).headers['server']
'Apache/2.2.22 (Debian)'
hostname = urllib.parse.urlparse(url).netloc
print (whois.whois(hostname))

sending a binary message using stream_socket_client and php strings

I am using php to connect to a socket server to send binary data - ie not standard ascii (or printable) strings. For example a message may contain ascii 0 or any number from 0 - 255.
I have functions for example like this:
function append_uint16($str, $num) {
$str += chr($num % 256);
$num /= 256;
$str += chr($num);
return $str;
}
It is called like this:
$msg = "\xA7\xA7";
$payload_size = 9 + 1 + strlen($param1) + 1 + strlen($param2);
$msg += append_uint16($msg, $payload_size);
Then I am sending to a socket server like this:
function send_msg($host, $port, $msg) {
$fp = stream_socket_client("tcp://" . $host . ":" . $port, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, $msg);
}
}
But the messages are not correctly formed. I suspect that my string processing is not quite correct. Or maybe I can't use strings in php in this way? Any ideas?

How do I Add Parsing JSON to PHP Script

So here's my sample code that I pull from SEOMOZ API for links on a targeted URL.
this script is command line
#!/usr/bin/php
<?php
$objectURL = $domain_url;$accessID = "xyz";
$secretKey = "xya";
$expires = mktime() + 300;
$stringToSign = $accessID."\n".$expires;
$binarySignature = hash_hmac('sha1', $stringToSign, $secretKey, true);
$urlSafeSignature = urlencode(base64_encode($binarySignature));
$urlToFetch = "http://lsapi.seomoz.com/linkscape/links/".urlencode($objectURL)."?AccessID=".$accessID."&Expires=".$expires."&Signature=".$urlSafeSignature."&SourceCols=26&&TargetCols=4&Scope=page_to_domain&Filter=follow&Sort=page_authority&Limit=10";
$handle = fopen($urlToFetch, "r");
$links_contents = '';
while (!feof($handle)) {
$links_contents .= fread($handle, 8192);
}
fclose($handle);
echo $links_contents;
?>
the result of the script is that it returns info in JSON format but in a huge glob not in an orderly manner. Whats the easiest way to format the result into a more neater/readable display?
here is the return from JSON
{
"frid": 1,
"lf": 2,
"lrid": 3,
"lsrc": 4,
"ltgt": 5,
"luuu": 6,
"prid": 7,
"ufq": 8,
"upl": 9,
"urid": 10
}
You mean json_decode($links_contents)?

Categories