简体   繁体   English

在PHP bluemix容器中运行mqtt python脚本

[英]Running mqtt python script in PHP bluemix container

I am running a PHP code on docker container hosted in Bluemix. 我正在Bluemix托管的docker容器上运行PHP代码。 The PHP code calls a python script which is a MQTT based subscribe code. PHP代码调用python脚本,该脚本是基于MQTT的订阅代码。 My idea was everytime the subscribed code gets MQTT message it will write the values to a text file. 我的想法是,每当订阅的代码获取MQTT消息时,它将把值写入文本文件。 The PHP code will keep on checking every 10 seconds for new values in the file. PHP代码将每10秒检查一次文件中的新值。 The VCAP_ENV variables are getting written correctly. VCAP_ENV变量正在正确写入。 However, the site does not load. 但是,该站点不会加载。

The python script executes successfully when i try it locally. 当我在本地尝试时,python脚本成功执行。 So no errors there too. 所以那里也没有错误。 My code is as follows: 我的代码如下:

PHP CODE: PHP代码:

<?php

if( getenv("VCAP_SERVICES") ) {


// get IoT service configuration from Bluemix


$services = getenv("VCAP_SERVICES");
$services_json = json_decode($services, true);

$mysql_config = $services_json["iotf-service"][0]["credentials"];

$org_id = $mysql_config["org"];


$port = $mysql_config["mqtt_u_port"];


$username = $mysql_config["apiKey"];


$password = $mysql_config["apiToken"];


}

// set configuration values
$config = array(
  'org_id' => $org_id,
  'port' => $port,
  'app_id' => 'mymqttfinalservice',
  'iotf_api_key' => $username,
  'iotf_api_secret' => $password,
  'device_id' => '007',
  'qos' => 1

);

$file = fopen("VCAP_CONFIG.ini","w");


#fwrite($file,"[config]" . PHP_EOL );
#fwrite($file,"org =" . $org_id . PHP_EOL );
#fwrite($file,"apikey =" . $username . PHP_EOL );
#fwrite($file,"authkey =" . $password . PHP_EOL );

fwrite($file,"[config]" . "\n" );
fwrite($file,"org =" . $org_id . "\n" );
fwrite($file,"apikey =" . $username . "\n" );
fwrite($file,"authkey =" . $password . "\n" );


fclose($file);

$file = file_get_contents('VCAP_CONFIG.ini', true);
echo $file;



$command = 'chmod 777 /app/PythonSubscribeCode.py';
$output = '';
exec ( $command);



$command = 'python3 /app/PythonSubscribeCode.py 2>&1';
$output = exec ($command);
print_r($output);


$x = 1;
while($x == 1)
{
  $config = parse_ini_file('Data.ini');
  echo json_encode($config);
  sleep(5);
}

?>

Python Script: Python脚本:

# -*- coding: utf-8 -*-

#!/usr/bin/env python3

import paho.mqtt.client as mqtt
import os, json
import time
import configparser

# This is the Subscriber

settings = configparser.ConfigParser()
settings.read('VCAP_CONFIG.ini')

organization = settings['config']['org']
username = settings['config']['apikey']
password = settings['config']['authkey']


#Set the variables for connecting to the iot service
broker = ""
devicename = "007"
topic = "iot-2/type/DesktopApplication/id/007/evt/status/fmt/json"
#topic = 'iot-2/evt/status/fmt/json'
deviceType = "DesktopApplication"

clientID = "a:" + organization + ":appId"

print (clientID)

broker = organization + ".messaging.internetofthings.ibmcloud.com"
mqttc = mqtt.Client(clientID)

if username is not "":
 mqttc.username_pw_set(username, password=password)


def on_connect(client, userdata, flags, rc):
 print("Connected with result code "+str(rc))

def on_subscribe(mosq, obj, mid, granted_qos):
 print("Subscribed: " + str(mid) + " " + str(granted_qos))


def on_message(mosq, obj, msg):
    global message
    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))

def on_message(client, userdata, msg):
     writeData = msg.payload.decode('utf-8')
     parsed_json = json.loads(writeData)
     UDD = parsed_json['UDD']
     DDD = parsed_json['DDD']
     PH = parsed_json['PH']
     Ignition = parsed_json['Ignition']

     # add the settings to the structure of the file, and lets write it out...
     config = configparser.ConfigParser()
     config['Data'] = {'UDD': UDD,
                      'DDD': DDD,
                      'PH': PH,
                  'Ignition':Ignition}
     with open('Data.ini', 'w') as configfile:
      config.write(configfile)

mqttc.connect(host=broker, port=1883, keepalive=60)
test = mqttc.subscribe(topic,0)

#print (test)
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message

mqttc.loop_forever()

Can someone please guide on this? 有人可以指导吗?

Do you get any useful error messages from cf ic logs containerid to see what might be failing? 您是否从cf ic logs containerid获得了任何有用的错误消息,以查看可能出了什么问题? As an alternate, you could also try execing into the container (either cf ic exec -ti containerid bash or docker exec... ) and run the python script directly to see if that's giving you other errors when running there. 另外,您也可以尝试执行到容器中( cf ic exec -ti containerid bashdocker exec... )并直接运行python脚本,以查看在该cf ic exec -ti containerid bash运行时是否还会给您其他错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM