【问题标题】:Running mqtt python script in PHP bluemix container在 PHP bluemix 容器中运行 mqtt python 脚本
【发布时间】:2017-01-18 14:38:17
【问题描述】:

我正在 Bluemix 中托管的 docker 容器上运行 PHP 代码。 PHP 代码调用一个 python 脚本,它是一个基于 MQTT 的订阅代码。我的想法是每次订阅的代码收到 MQTT 消息时,它都会将值写入文本文件。 PHP 代码将每 10 秒检查一次文件中的新值。 VCAP_ENV 变量正在正确写入。但是,该网站无法加载。

当我在本地尝试时,python 脚本成功执行。所以那里也没有错误。 我的代码如下:

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 脚本:

# -*- 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()

有人可以指导一下吗?

【问题讨论】:

  • 我将假设 php 构建包不包含 python 解释器或任何 pip 安装 MQTT 模块的方式
  • @hardlib 它包含 python 解释器。如果有任何错误,它确实会给出其他错误。此外,如果我尝试 PHP 的 mqtt 代码,它可以工作。但是,我不想一直刷新网页,这就是我选择 python 实现的原因。
  • @hardillb 原因可能是因为 Python 脚本是一个订阅代码,它永远不会退出执行,因此控制永远不会回到 PHP 代码?

标签: php python containers ibm-cloud mqtt


【解决方案1】:

您是否从cf ic logs containerid 收到任何有用的错误消息以查看可能出现的问题?作为替代方案,您也可以尝试执行到容器中(cf ic exec -ti containerid bashdocker exec...)并直接运行 python 脚本以查看在其中运行时是否会出现其他错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2014-08-02
    • 2021-09-06
    • 1970-01-01
    • 2020-12-31
    • 2011-07-17
    • 2017-05-23
    • 1970-01-01
    相关资源
    最近更新 更多