Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent MQTT Client exception #822

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 23 additions & 14 deletions scripts/phpmqtt_input.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,10 @@
$device = new Device($mysqli,$redis);
}

$mqtt_client = new Mosquitto\Client();
$mqtt_client = new Mosquitto\Client($id=$user->get_apikey_write($mqttsettings['userid'],$cleanSession=false));

$connected = false;
$subscribed = 0;
$last_retry = 0;
$last_heartbeat = time();
$count = 0;
Expand All @@ -119,21 +120,29 @@
}

if (!$connected && (time()-$last_retry)>5.0) {
$subscribed = 0;
$last_retry = time();
try {
$log->warn("Not connected, retrying connection");
$mqtt_client->setCredentials($mqtt_server['user'],$mqtt_server['password']);
$mqtt_client->connect($mqtt_server['host'], $mqtt_server['port'], 5);
} catch (Exception $e) {
$log->error($e);
}
}

if ($connected && ($subscribed == 0)) {
try {
$topic = $mqtt_server['basetopic']."/#";
//echo "Subscribing to: ".$topic."\n";
$log->info("Subscribing to: ".$topic);
$mqtt_client->subscribe($topic,2);
$subscribed = $mqtt_client->subscribe($topic,2);
$log->info("Subscribed to: ".$topic." ID - ".$subscribed);
} catch (Exception $e) {
$log->error($e);
$subscribed = 0;
}
//echo "Not connected, retrying connection\n";
$log->warn("Not connected, retrying connection");
}

if ((time()-$last_heartbeat)>300) {
$last_heartbeat = time();
$log->info("$count Messages processed in last 5 minutes");
Expand All @@ -145,32 +154,32 @@
die;
}
}

usleep(1000);
}


function connect($r, $message) {
global $log, $connected;
$connected = true;
//echo "Connected to MQTT server with code {$r} and message {$message}\n";
// set connected flag if CONNACK is 0 (success)
$connected = ($r == 0);
$log->warn("Connecting to MQTT server: {$message}: code: {$r}");
}

function subscribe() {
global $log, $topic;
//echo "Subscribed to topic: ".$topic."\n";
$log->info("Subscribed to topic: ".$topic);
$log->info("Callback subscribed to topic: ".$topic);
}

function unsubscribe() {
global $log, $topic;
global $log, $topic, $subscribed;
//echo "Unsubscribed from topic:".$topic."\n";
$subscribed = 0;
$log->error("Unsubscribed from topic: ".$topic);
}

function disconnect() {
global $connected, $log;
global $connected, $log, $subscribed;
$subscribed = 0;
$connected = false;
//echo "Disconnected cleanly\n";
$log->info("Disconnected cleanly");
Expand Down