How to convert a php scfript to python?

I would like to convert a working php script that now runs as a service and parses data to a mqtt broker. The goal is to have it converted to a python script for HA.

What it does:
Reading a Visonic powerlink 3 interface’s sensors and panelstate.
Every 2 seconds it authenticates with a json string via http to a local ipaddress with specific port.
If the data is read, the data is written to a mqtt broker (which seems a step that can be left out if the request goes directly to HA)

This is the script that is running:

<?php
$sleeptimer=2; //seconds
$remoteserveraddress="192.168.x.x";  //response address for the visonic interface to respond to
$visonic_pin = "8888";
$id=30; // connecting ID
$baseurl= "http://192.168.x.x:8181"; // address from the visonic powerlink 3 ,used in the curl connector 

//mqtt settings
$address = "192.168.x.x"; //mqtt server address
$port = 1883;
$username="mqtt"; //mqtt user
$password="pw"; //mqtt password
$topic = "Visonic/Powermaster30/";
$client_id = "visonic";
$will = array("topic" => "Visonic/Powermaster30/online" , "content" => "offline" , "retain" => "0","qos" => "0");
$timesinceping=time();

$deviceIds=array(2,4,7,8,16,17,18,29,30); //which devices to scan
$previousdevicestate=array();
$previouspanelstate=array();

require 'phpMQTT.php'; // mqtt script
$mqtt = new Bluerhinos\phpMQTT($address, $port, $client_id);

class subscribe
{	
	public function connect ($data)
		{	
		global $baseurl;
		$url = $baseurl."/remote/json-rpc";
			$data_string = json_encode($data);
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Content-Type: application/json',
				'Content-Length: ' . strlen($data_string))
				
			);
			
			$result = curl_exec($ch);
			$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	
	if(curl_errno($ch)){
    echo 'Request Error:' . curl_error($ch);
}

	curl_close($ch);
			return $result;
		}
}

// visonic powerlink 3 examples
//{"params": ["192.168.x.x", 8888, "user"],"jsonrpc": "2.0","method":"PmaxService/registerClient", "id":1}

//{"params": null,"jsonrpc":"2.0","method":"PmaxService/getLocationsList", "id":1}

//{"params": [ 14 ],"jsonrpc":"2.0","method":"PmaxService/getZoneDeviceTemperature", "id":1}


//{"params": [ 3,14 ],"jsonrpc":"2.0","method":"PmaxService/getDeviceStatuses", "id":1}

//{"params": [ 3,1 ],"jsonrpc":"2.0","method":"PmaxService/getDeviceConfig", "id":1}

//{"params": [ 2 ],"jsonrpc":"2.0","method":"PmaxService/getPanelState", "id":5} HOME, DISARM, AWAY, HOME_EXIT_DELAY, AWAY_EXIT_DELAY

// {"params": [ "<code>", "DISARM", 2, true, true ],"jsonrpc":"2.0","method":"PmaxService/setPanelState", "id":5} HOME, DISARM, AWAY

$auth = json_decode('{"params": ["'.$remoteserveraddress.'", '.$visonic_pin.', "user"],"jsonrpc": "2.0","method":"PmaxService/registerClient", "id":'.$id.'}');
	
while(true){
if (php_sapi_name() != "cli") {
	echo "<pre>";
}

$a = new subscribe();
$result = $a->connect($auth);
$auth= json_decode($result,true);

if ($auth['result']['status']=='success'){
	if ($mqtt->connect(true, null, $username, $password)) {
		echo "MQTT Visonic Online\n";
		$mqtt->publish($will['topic'], "online", 0,1);
		$mqtt->close();
	}else{
		echo "MQTT Visonic fail or time out\n";
	}

	$numberofdevices=count($deviceIds);	
	for ($x = 1; $x <= $numberofdevices; $x++) {
		$jsondata = json_decode('{"params": [ 3,'.$deviceIds[$x-1].' ],"jsonrpc":"2.0","method":"PmaxService/getDeviceStatuses", "id":'.$id.'}');
		$a = new subscribe();
		$result = $a->connect($jsondata);
		$data['result']['statuses']['open']="";
		$data = json_decode($result,true);
		if($data['error']['code'] == '-32001'){
			$status="error";
		}
		else{
			if ($data['result']['statuses']['open'] == "1"){
				$status="open";
			}
			else {
				$status="closed";
			}
			if ($mqtt->connect(true, null, $username, $password)) {
					$mqtt->publish($topic."devices/".$deviceIds[$x-1], $status, 0);
					$mqtt->close();
			}else{
				echo "MQTT Visonic fail or time out\n";
			}
		}
			echo $deviceIds[$x-1]." ".$status."\n";	
	}	
	
// get panelstate for 3 zones
	for ($x = 1; $x <= 3; $x++) {
		$jsondata = json_decode('{"params": ['.$x.'] ,"jsonrpc":"2.0","method":"PmaxService/getPanelState", "id":'.$id.'}');

		$a = new subscribe();
		$result = $a->connect($jsondata);
		$data['result']['state']="";
		$data = json_decode($result,true);
		echo "Partition: ".$x." : ".$data['result']['state']."\n";
		$previouspanelstate[$x-1]=$data['result']['state'];

		if ($mqtt->connect(true, null, $username, $password)) {
			switch ($data['result']['state']) {
				case "HOME":
					$mqttpanelstate = "armed_home";
					 break;
				case "AWAY":
					$mqttpanelstate = "armed_away";
					 break;
				case "DISARM":
					$mqttpanelstate = "disarmed";
					 break;				   
				case "HOME_EXIT_DELAY":
					$mqttpanelstate = "pending";
					 break;
				case "AWAY_EXIT_DELAY":
					$mqttpanelstate = "pending";
					break;
			}
			if($data['result']['state'] != ""){
				$mqtt->publish($topic."panelstate/partition/".$x, $mqttpanelstate, 0);
				$mqtt->close();
			}
		}else{
			echo "MQTT Visonic fail or time out\n";
		}
	}	
}
else {
	echo"Could not connect Visonic\n";
}
if (php_sapi_name() != "cli") {
	
	echo "Script did not run from CLI\n";
	die;
}
sleep ($sleeptimer);

}


It is not the best and cleanest code. This is only used for testing the capabilities of HA and the Powerlink3 interface (which has no official documentation at all for the syntax and options)

Who want to help with porting this code to HA Python?
For me it is learning how HA custom code works and is implemented.

You have two issues, converting to python, and making a ha integration. (If you leave it as mqtt you can forget the second bit, and that will be way simpler, but it sounds like you want to learn tge second bit!).

Look at the top of the page click the developer docs page.

Then look at the code on github. Learning by example.

PS could this be done with the rest sensor couldn’t it?

I would like to integrate it so it is not dependent on a separate server and a mqtt broker between.

The REST sensor could be an option. The part which is not covered is the authentication that is done with a JSON string too. This gives a response if the connection is done right. If so, then read the sensors. I don’t see an option that I can do two steps at once with a control step between it.

Node Red was also an option but not stable enough to me.
Python looks the best way. Python is not the issue for me but the way how HA works is not that clear for custom components.

I have opened a custom component that has been loaded via HACS. I see 3 files that represent the integration.

__init__.py
manifest.json
sensor.py

I will check the files together with the docs (which are way more clear than one year ago)

Hi NielsS,

Looking for an IP connection to my Powermaster 360R having a Powerlink on board. Did you have any progress? Is your Powermaster 30 using a connection to a Powermanage server?

Regards, Charles

I changed the php script and built in some checks that the MQTT connection is working better and instant instead of with a timed loop.

The script is built to communicate to a Powerlink 3 board. That board is also talking to the Visonic-Go app to Tycomonitor.
With the php script I am directly talking to the board with http and JSON. It works well but want something more reliable with a direct connection to HA.

Are you developing something too? Then we can cooperate.

Does this thread help? Visonic Powermax and Powermaster Component

I have tried it before and discovered that the version of firmware running in my Powermaster 30 was not compatible. The issue was that it tried to communicate and got into negotiation but then ended unsuspected and got into an endless loop trying with no repsonse.

But thanks for noticing it and I will try it with the latest release of the HA component to see if this version works better.

Perhaps an issue posted on the existing custom component github?