I'm using Raspberry-pi to read data from epever by rs485 to usb.I'm using this PHP file to read data.
<?php
/*
* PHP EpSolar Tracer Class (PhpEpsolarTracer) v0.9
*
*/
//EPEver tracer php library
require_once 'PhpEpsolarTracer.php';
//influxDB php client library
require 'vendor/autoload.php';
//Define IP of influxDB
$host = 'localhost';
$tracer = new PhpEpsolarTracer('/dev/ttyUSBACM0');
$client = new InfluxDB\Client($host,8086,"root","root");
$db = $client->selectDB("logger");
//'http://localhost:8086/write?db=mydb' --data-binary 'cpu_load_short,host=server01,region=us-west value=0.64 1434055562000000000'
Print "\n Realtime Data\n";
if ($tracer->getRealtimeData()) {
for ($i = 0; $i < count($tracer->realtimeData); $i++) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8086/write?db=powerwall" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$Item = $tracer->realtimeData[$i];
$Key_Name = str_replace(" ","-",$tracer->realtimeKey[$i]);
Print str_pad($i, 2, '0', STR_PAD_LEFT) . " " . $Key_Name . " " . $Item . "\n";
curl_setopt($ch, CURLOPT_POSTFIELDS, "$Key_Name,unit=Realtime value=$Item" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result = curl_exec ($ch);
}
} else
print "Cannot get RealTime Data\n";
Print "\n Statistical Data\n";
if ($tracer->getStatData()) {
for ($i = 0; $i < count($tracer->statData); $i++) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost:8086/write?db=powerwall" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$Item = $tracer->statData[$i];
$Key_Name = str_replace(" ","-",$tracer->statKey[$i]);
$Key_Name = 'Stat-' . $Key_Name;
Print str_pad($i, 2, '0', STR_PAD_LEFT) . " " . $Key_Name . " " . $Item . "\n";
curl_setopt($ch, CURLOPT_POSTFIELDS, "$Key_Name,unit=statData value=$Item" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result = curl_exec ($ch);
}
} else
print "Cannot get Statistical Data\n";
?>
When I run this code I got the error message:
Cannot get Real Time Data
So then I followed the issue in here:
Modbus cant read data from epever tracer 1210a to raspberry
But I haven't do this, I got several errors.
Then I have checked the kernel version of my raspberry pi and it shows as
Linux raspberry pi 4.19.57-v7+ #1244 SMP Thu Jul 4 18:45:25 BST 2019 armv7l GNU/Linux
Related
I am calling the Binance Klines API to get current prices.
// Get Assets - ideally I'd just like the currency name (e.g. ETH) rather ETC/BTC
$url = 'https://api.binance.com/api/v3/exchangeInfo';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$result = curl_exec($ch);
curl_close($ch);
$json = json_decode($result);
foreach($json->symbols as $symbol)
{
// Get prices for teh asset
$ccode = $symbol->symbol;
$nurl = 'https://api.binance.com/api/v3/klines?symbol=' . $ccode . '&interval=1m';
$stime = 1000*(time() - 60); // Time period is the last minute
$etime = 1000*time();
$nurl .= '&startTime=' . $stime;
$nurl .= '&endTime=' . $etime;
$ch = curl_init($nurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $nurl);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$json = curl_exec($ch);
curl_close($ch);
if ( $json === "" || $json === "[]" || substr($json, 0, 8) == '{"code":' )
{
echo "Not found " . $ccode . " .. skipping <BR>";
continue;
}
$arr = explode(",", $json);
$price = $arr[4];
$tstamp1 = $arr[6];
$tstamp = gmdate("Y-m-d\TH:i:s\Z", ($arr[6]/1000));
echo $ccode . " " . $tstamp . " " . $price . "<BR>";
}
The problem is I get all combinations of coin/currency, when I only want the GBP prices for each coin. The full list about times out as it runs for over 5 minutes.
I'd like to just get the price of each coin in GBP.
How can I do that?
You're asking for all the symbols (exchangeInfo) and then getting the candle info (klines) for each symbol (= currency pair).
You can do so just for the GBP pairs by looking for GBP in the two currencies you're currently iterating on, by adding this to your foreach:
// rest of the code
foreach($json->symbols as $symbol)
{
if ($symbol->baseAsset === "GBP" || $symbol->quoteAsset === "GBP" ) {
// rest of your foreach
}
}
In your foreach you have these three properties under $symbol you can leverage:
$symbol->symbol // "ADAGBP"
$symbol->baseAsset // "ADA"
$symbol->quoteAsset // "GBP"
I'm trying to add a job to the Workflow Max API. I seem to be hitting the API but I keep getting the error message:
Message not in expected format. The following required element was missing - Job/ClientID
I'm sure that the client ID is added but something seems to be wrong. This is the code:
function post_job_to_workflow_max($job_data) {
// configure our connection to the api
$api_token = 'API_KEY';
$acc_key = 'ACC_TOKEN';
$url = 'https://api.workflowmax.com/job.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Job data must match the format required by WorkflowMax
// currently accepts XML data
// see: https://www.workflowmax.com/api/job-methods#POST%20add
$xml = new SimpleXMLElement("<Job></Job>");
$xml->addChild('Name', $job_data[0]);
$xml->addChild('Description', $job_data[1]);
$xml->addChild('ClientID', 18754031);
// $clientID = $xml->addChild('Client');
// $clientID->addChild('ID', 18754031);
// $clientID->addChild('Name', "TEST CLIENT");
$xml->addChild('State', 'Planned');
$xml->addChild('StartDate', $job_data[2]);
$xml->addChild('DueDate', $job_data[3]);
// print_r($xml);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
$result = simplexml_load_string($output);
print_r($result);
}
If there's anyone with experience of using WFM, would be good to hear how you approached it.
Thanks
So in answer to my own question, I did finally work this out.
The way I did this was to return the ID of the client from the function I used to post a client to WorkFlow Max. See code:
1) post the client
function post_client_to_workflowmax($client_data) {
// configure our connection to the api
$api_token = 'YOUR_TOKEN';
$acc_key = 'YOUR_KEY';
$url = 'https://api.workflowmax.com/client.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Client data must match the format required by WorkflowMax
// currently accepts XML data
// These indexes match up with how the data has been stored
// see: https://www.workflowmax.com/api/client-methods#POST%20add
$xml = new SimpleXMLElement("<Client></Client>");
$xml->addChild('Name', htmlspecialchars($client_data[2]));
$xml->addChild('Email', htmlspecialchars($client_data[9]));
$xml->addChild('Phone', htmlspecialchars($client_data[10]));
$xml->addChild('Address', htmlspecialchars($client_data[3]) . ' ' . htmlspecialchars($client_data[4]));
$xml->addChild('City', htmlspecialchars($client_data[5]));
$xml->addChild('Postcode', htmlspecialchars($client_data[7]));
$xml->addChild('Country', htmlspecialchars($client_data[8]));
$xml->addChild('IsProspect', 'No');
$contacts = $xml->addChild('Contacts');
$contact = $contacts->addChild('Contact');
$name = $contact->addChild('Name', htmlspecialchars($client_data[0]) . ' ' . htmlspecialchars($client_data[1]));
// POST request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
// Create an array from the data that is sent back from the API
$result = simplexml_load_string($output);
$clientID = NULL;
// here we get the ID created for this client and pass it into the variable $clientID
foreach($result->Client as $k => $v) {
$clientID = $v->ID;
}
return $clientID;
}
We then get that ID passed into our job posting function like so:
2) post a job to WFM
function post_job_to_workflow_max($job_data, $clientID) {
// configure our connection to the api
$api_token = 'YOUR_TOKEN';
$acc_key = 'YOUR_KEY';
$url = 'https://api.workflowmax.com/job.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Job data must match the format required by WorkflowMax
// currently accepts XML data
// see: https://www.workflowmax.com/api/job-methods#POST%20add
$xml = new SimpleXMLElement("<Job></Job>");
$xml->addChild('ClientID', $clientID);
$xml->addChild('Name', htmlspecialchars($job_data[0]));
$xml->addChild('Description', htmlspecialchars($job_data[1]));
$xml->addChild('State', 'Planned');
$xml->addChild('StartDate', htmlspecialchars($job_data[2]));
$xml->addChild('DueDate', htmlspecialchars($job_data[3]));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
$result = simplexml_load_string($output);
}
And then calling these functions looks something like this:
$id = post_client_to_workflowmax($client);
post_job_to_workflow_max($job, $id);
Where $client must be an array of data. This worked for my case but might not work for your particular case so you may need to edit the fields etc.
Hopefully this helps someone who is stuck with the same problem. Not the most elegant code but it gets the job done.
I'm trying to use an API that requires authentication with a private key pair.
Here is the API documentation:
Authentication API Docs
SubmitOrder API Docs
This is my code. I'm not getting any errors, but no trades are being placed. My coding skills are not the sharpest and without errors, I'm stuck!
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
// Generate random amount between 28.00 and 30.00
$ran1 = mt_rand(2800, 3000);
$ran2 = $ran1/100;
// Config
$sAPIKey = "mykey"; // private key
$sAPISecret = "mysecret"; // api secret
$sPair = "GLD_BTC";
// $sAmount = "1.00";
$sRate = "0.0001";
$sNonce = time();
// Request
$sRequest = "https://tradesatoshi.com/api/private/submitorder?API_PUBLIC_KEY=" . $sAPIKey . "&Market=" . $sPair . "&Type=" . 'Buy' . "&Amount=" . $ran2 . "&Price=" . $sRate . "&nonce=" . $sNonce;
$sSign=hash_hmac('sha512', $sRequest, $sAPISecret);
$ch = curl_init($sRequest);
// disable cert validation
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // shouldn't need this
// curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:' . $sSign));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('apisign:' . $sSign));
$execResult = curl_exec($ch);
?>
Any guidance would be sincerely appreciated.
I have a PHP script that uploads files into Dropbox. When I run it from command-line as a standalone script, it works perfectly.
However, when I incorporate my code into the larger project, the file fails to upload, cURL returns "errno" 0 (meaning, no cURL errors), and there's no output from Dropbox's API.
Here is the code that works:
$token = '<token>';
$url = "https://content.dropboxapi.com/2/files/upload";
$post_body = file_get_contents("/other/server/url/test.txt");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token,
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: {"path": "/Dropbox/path/subfolder/test.txt","mode": "add", "autorename": true, "mute": false}'));
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($data);
.... and here is the broken code:
private function dropbox_uploadFile( $path, $file_source, $file_name = "test1.txt") {
echo "<br /><br />PATH: ". $path . '/' . $file_name . "<br /><br />";
echo "<br /><br />SOURCE: ". $file_source . "<br /><br />";
$token = '<token>';
$url = "https://content.dropboxapi.com/2/files/upload";
$post_body = file_get_contents( $file_source );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token,
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: {"path": ' . $path.'/'.$file_name. '","mode": "add", "autorename": true, "mute": false}'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false); // to prevent cURL error #60
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = json_decode(curl_exec($ch), true);
if( ! $data ) {
echo "<pre>";
print_r(curl_getinfo($ch));
echo "</pre>";
echo "ERROR: " . curl_errno( $ch ) . "<br /><br />";
}
curl_close($ch);
print_r($data);
}
I broke out the API call itself, like this:
$res = curl_exec($ch);
print_r($res);
$data = json_decode($res, true);
That showed me the actual error from the API:
Error in call to API function "files/upload": HTTP header "Dropbox-API-Arg": could not decode input as JSON
For different types of errors, the API will return either plain text or JSON, with the response Content-Type header telling you which. In your code, you were only handling JSON, and json_decode apparently silently fails when it isn't supplied valid JSON.
Anyway, that error indicates the supplied JSON for the upload arguments is itself invalid. The problem seems to be a missing quote at the beginning of the path value, fixed here:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token,
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: {"path": "' . $path.'/'.$file_name. '","mode": "add", "autorename": true, "mute": false}'));
I went here trying some tips, and I ma using SWIFT.
Hope can help OTHERS.
After some (hard) mailing with dropbox support...
Error in my case was due to unescaping special chars in path.
If You want to upload:
let unescapedFileName = "αβγ.jpg"
You have to escape:
let unescapedFileName = "αβγ.jpg"
let escapedFileName = DB_asciiEscape(unescapedFileName)
Here an Unit test:
func testUtf8Decode(){
let unescapedFileName = "αβγ.jpg"
let escapedFileName = DB_asciiEscape(unescapedFileName)
print(escapedFileName)
let contains = escapedFileName.contains("\\u03b1\\u03b2\\u03b3")
XCTAssert(contains, "not escaped")
}
where function is:
func DB_asciiEscape(_ s: String) -> String {
let out = s.unicodeScalars.reduce("", { (partialResult: String, char: UnicodeScalar) -> String in
if !char.isASCII {
return partialResult + String(format:"\\u%04x", char.value)
} else {
if (char == "\u{7F}") {
return partialResult + "\\u007f"
} else {
return partialResult + "\(char)"
}
}
})
return out
}
I have the ZF first old function working before but somehow ZF it was failing, and then i made the unittest module.
I am trying to use the google translation v2 but it never works anymore, did Google stop there service for public use or is it PHP Bug or somewhere else confusing very much.
Always returning 403 with both following functions.
Any idea whats going wrong?
<?php
## Test: How to's
/*
$ php tst.php
403
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}sun#sun-M14xR2:/var/www/html/vooyz.com/unittest$
*/
// V1 - Old not working
function googleTranslatePostV1($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'http://ajax.googleapis.com/ajax/services/language/translate';
$http_response = '';
$text = urlencode($text);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "v=1.0&q=" . $text . "&langpair=$srcLang|$destLang");
$http_response = curl_exec($ch);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Curl way not working
function googleTranslatePostV2($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'https://www.googleapis.com/language/translate/v2';
$http_response = '';
$text = urlencode($text);
$postArr = array('key' => 'sdfdsfdsfds',
'q' => $text,
'source' => $srcLang,
'target' => $destLang);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_POSTFIELDS,'hl=en&ie=UTF8&text=-->this+is+a+test<--&langpair=en%7Car');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postArr);
$http_response = curl_exec($ch);
var_dump($http_response);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Google way
function googleTranslateV2Method1($text, $destLang = 'nl', $srcLang = 'en') {
require_once 'google/src/Google_Client.php';
require_once 'google/src/contrib/Google_TranslateService.php';
$client = new Google_Client();
$client->setApplicationName('Google Translate PHP Starter Application');
$client->setDeveloperKey('dsfdsfdsf');
$service = new Google_TranslateService($client);
//$langs = $service->languages->listLanguages();
//print "<h1>Languages</h1><pre>" . print_r($langs, true) . "</pre>";
$translations = $service->translations->listTranslations($text, 'hi');
return $translations;
}
echo googleTranslatePostV1("V1: " . "How are you?") . "\n";
echo googleTranslatePostV2("V2: " . "How are you?") . "\n";
echo googleTranslateV2Method1("V2: " . "How are you?") . "\n";
?>
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}
http://code.google.com/apis/language/translate/overview.html : Google
Translate API is available as a paid service. See the Pricing and FAQ
pages for details.