function PostaviVrijednost($topic, $message) { $mqtt = new phpMQTT("localhost", 1883, "PHP MQTT Publisher"); if ($mqtt->connect()) { $mqtt->publish($topic, $message, 0); $mqtt->close(); } }
<?php require "phpMQTT.php"; ?> <html> <body> <form action="publish.php" method="POST"> Topic: <input type="text" name=topic><br> Message: <input type="text" name=message><br> <input type="submit" value="Submit"> </form> </body> </html> <?php if (isset($_REQUEST['topic'])) { $mqtt = new phpMQTT("localhost", 1883, "PHP MQTT Publisher"); if ($mqtt->connect()) { echo "Published TOPIC:" . " " . $_REQUEST['topic'] . "<br>"; echo "Published MESSAGE:" . " " . $_REQUEST['message'] . "<br>"; $mqtt->publish($_REQUEST['topic'], $_REQUEST['message'], 0); $mqtt->close(); } }
function PostaviVrijednost($topic, $message) { $mqtt = new phpMQTT("localhost", 1883, "PHP MQTT Publisher"); // NAPOMENA: Ukoliko bude potrebno, podesiti odgovarajuće address i clientid if ($mqtt->connect()) { $mqtt->publish($topic, $message, 0); $mqtt->close(); } }
<?php require "phpMQTT.php"; $mqtt = new phpMQTT("example.com", 1883, "phpMQTT Test Publisher"); if ($mqtt->connect()) { $mqtt->publish("tree", '{"mode":"blink"}'); $mqtt->close(); }
<?php // include class require 'phpMQTT.php'; // set configuration values $config = array('org_id' => 'IOTF-ORG-ID', 'port' => '1883', 'app_id' => 'phpmqtt', 'iotf_api_key' => 'IOTF-API-KEY', 'iotf_api_secret' => 'IOTF-API-TOKEN', 'maps_api_key' => 'GOOGLE-API-KEY', 'device_id' => 'DEVICE-ID', 'qos' => 1); $config['server'] = $config['org_id'] . '.messaging.internetofthings.ibmcloud.com'; $config['client_id'] = 'a:' . $config['org_id'] . ':' . $config['app_id']; $location = array(); // initialize client $mqtt = new phpMQTT($config['server'], $config['port'], $config['client_id']); $mqtt->debug = false; // connect to broker if (!$mqtt->connect(true, null, $config['iotf_api_key'], $config['iotf_api_secret'])) { echo 'ERROR: Could not connect to IoT cloud'; exit; } // subscribe to topics $topics['iot-2/type/+/id/' . $config['device_id'] . '/evt/accel/fmt/json'] = array('qos' => $config['qos'], 'function' => 'getLocation'); $mqtt->subscribe($topics, $config['qos']); // process messages $elapsedSeconds = 0; while ($mqtt->proc(true)) { if (count($location) == 2) { $latitude = $location[0]; $longitude = $location[1]; $mapsApiUrl = 'https://maps.googleapis.com/maps/api/staticmap?key=' . $config['maps_api_key'] . '&size=640x480&maptype=roadmap&scale=2&markers=color:green|' . sprintf('%f,%f', $latitude, $longitude); break; } if ($elapsedSeconds == 5) { break;
/** * Title * * Description * * @access public */ function setProperty($id, $value, $set_linked = 0) { $rec = SQLSelectOne("SELECT * FROM mqtt WHERE ID='" . $id . "'"); if (!$rec['ID'] || !$rec['PATH']) { return 0; } include_once "./lib/mqtt/phpMQTT.php"; $this->getConfig(); if ($this->config['MQTT_AUTH']) { $username = $this->config['MQTT_USERNAME']; $password = $this->config['MQTT_PASSWORD']; } if ($this->config['MQTT_HOST']) { $host = $this->config['MQTT_HOST']; } else { $host = 'localhost'; } if ($this->config['MQTT_PORT']) { $port = $this->config['MQTT_PORT']; } else { $port = 1883; } $mqtt_client = new phpMQTT($host, $port, "MajorDoMo MQTT Client"); if (!$mqtt_client->connect(true, NULL, $username, $password)) { return 0; } $mqtt_client->publish($rec['PATH'], $value); /*$topic, $content, $qos = 0, $retain = 0*/ $mqtt_client->close(); if ($set_linked && $rec['LINKED_OBJECT'] && $rec['LINKED_PROPERTY']) { setGlobal($rec['LINKED_OBJECT'] . '.' . $rec['LINKED_PROPERTY'], $value, array($this->name => '0')); } }
$file = 'connected.txt'; // Open the file to get existing content $current = file_get_contents($file); // Append a new person to the file $current .= "1\n"; // Write the contents back to the file file_put_contents($file, $current); echo "<p>file written</p>"; } else { //same user do nothing } //check how many users have been connected //send to mqtt the dance command //check the connected.txt file: if (file_exists('connected.txt')) { $mqtt = new phpMQTT("iot.eclipse.org", 1883, "wso2con"); $file = "connected.txt"; $lines = count(file($file)); if ($lines > 2) { //send long dance command: if ($mqtt->connect()) { $mqtt->publish("wso2con", '2', 0); $mqtt->close(); } } else { //send short dance command: if ($mqtt->connect()) { $mqtt->publish("wso2con", '1', 0); $mqtt->close(); } }
} $host = 'localhost'; if ($mqtt->config['MQTT_HOST']) { $host = $mqtt->config['MQTT_HOST']; } if ($mqtt->config['MQTT_PORT']) { $port = $mqtt->config['MQTT_PORT']; } else { $port = 1883; } if ($mqtt->config['MQTT_QUERY']) { $query = $mqtt->config['MQTT_QUERY']; } else { $query = '/var/now/#'; } $mqtt_client = new phpMQTT($host, $port, $client_name); if ($mqtt->config['MQTT_AUTH']) { if (!$mqtt_client->connect(true, NULL, $username, $password)) { exit(1); } } else { if (!$mqtt_client->connect()) { exit(1); } } $topics[$query] = array("qos" => 0, "function" => "procmsg"); $mqtt_client->subscribe($topics, 0); $previousMillis = 0; while ($mqtt_client->proc()) { $currentMillis = round(microtime(true) * 10000); if ($currentMillis - $previousMillis > 10000) {
<?php include "resources/phpMQTT.php"; error_reporting(0); $results = []; $topics = "WEATHER/a,AHMS/pir,AHMS/move,AHMS/door"; if (isset($_GET["topic"])) { $topics = $_GET["topic"]; } $mqtt = new phpMQTT("192.168.1.20", 1883, "PHP MQTT Client", "ahmsclient", "ahms2013"); if ($mqtt->connect()) { foreach (explode(",", $topics) as $topic) { $myTopics = []; $myTopics[$topic] = array("qos" => 0, "function" => "procmsg"); $mqtt->subscribe($myTopics); if ($mqtt->proc() == 0) { array_push($results, array("status" => "no message", "topic" => $topic, "message" => "")); } } $mqtt->close(); } else { array_push($results, array("status" => "ok", "no connection" => $topic, "message" => "")); } echo json_encode($results); function procmsg($topic, $message) { global $results; array_push($results, array("status" => "ok", "topic" => $topic, "message" => $message)); }
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ require_once dirname(__FILE__) . '/phpMQTT/phpMQTT.php'; require_once dirname(__FILE__) . '/Database.php'; require_once dirname(__FILE__) . '/Rosenberg.php'; require_once dirname(__FILE__) . '/Config.php'; $oDB = new Database(Config::$sInfluxDBHost); $mqtt = new phpMQTT(Config::$sMQTTHost, Config::$iMQTTPort, "iws daemon"); if (!$mqtt->connect()) { exit(1); } $topics['/iws/+/soil_moisture'] = array("qos" => 0, "function" => "processMoisture"); $mqtt->subscribe($topics, 0); $oRosenberg = new Rosenberg($oDB); $mqtt->subscribe($oRosenberg->getTopics()); while ($mqtt->proc()) { } $mqtt->close(); function processMoisture($topic, $msg) { print "processing {$topic}:{$msg}\n"; global $oDB; $pTopic = "/\\/iws\\/(?P<sensor_id>MOIST_[0-9A-F]{8})\\/soil_moisture/"; if (!preg_match($pTopic, $topic, $aMatches)) { die("Couldn't match topic in {$topic}\n"); }
<?php echo "<script type='text/javascript'>\$(document).ready(function(){\n\t\tconsole.log('working hete');\n\t});</script>"; //publish.php require "phpMQTT.php"; $host = "m11.cloudmqtt.com"; $port = 14518; $username = "******"; $password = "******"; $message = "A000W010B000"; //MQTT client id to use for the device. "" will generate a client id automatically $mqtt = new phpMQTT($host, $port, "ClientID" . rand()); if ($mqtt->connect(true, NULL, $username, $password)) { $mqtt->publish("/sub/1", $message, 0); $mqtt->close(); } else { echo "Fail or time out<br />"; }
function nodes_controller() { global $route, $redis, $mysqli, $feed_settings, $session; $result = false; if (!$session['write']) { return array('content' => $result); } $emoncms_config_file = "/home/pi/data/emoncms.conf"; include "Modules/feed/feed_model.php"; $feed = new Feed($mysqli, $redis, $feed_settings); include "Modules/nodes/process.php"; $process = new Process($mysqli, $feed); if ($route->action == 'view') { $route->format = "html"; $result = view("Modules/nodes/nodes.php", array()); return array('content' => $result, 'fullwidth' => true); } elseif ($route->action == 'apidocs') { $route->format = "html"; $result = view("Modules/nodes/apidocs.html", array()); return array('content' => $result, 'fullwidth' => false); } if ($route->method == 'GET' || $route->method == 'POST' || $route->method == 'DELETE') { $route->format = "json"; $url = explode("/", rtrim($_GET['q'], "/")); $input = false; $input = file_get_contents('php://input'); if (isset($_GET['val'])) { $input = $_GET['val']; } $nodeid = false; $rxtx = false; $varid = false; $prop = false; if (isset($url[1]) && is_numeric($url[1])) { $nodeid = $url[1]; } if (isset($url[2])) { if (is_numeric($url[2])) { $varid = $url[2]; } elseif ($url[2] == "rx") { $rxtx = "rx"; if (isset($url[3]) && is_numeric($url[3])) { $varid = $url[3]; } } elseif ($url[2] == "tx") { $rxtx = "tx"; if (isset($url[3]) && is_numeric($url[3])) { $varid = $url[3]; } } } if ($varid) { $varid--; } // user index starts from 1, code index starts from 0 $propid = 1; if ($nodeid !== false) { $propid++; } if ($varid !== false) { $propid++; } if ($rxtx !== false) { $propid++; } if (isset($url[$propid])) { $prop = $url[$propid]; } if (!$redis->exists("config")) { $config = json_decode(file_get_contents($emoncms_config_file)); $redis->set("config", json_encode($config)); } else { $config = json_decode($redis->get("config")); } if ($route->method == 'POST') { $config_changed = false; // if ($nodeid===false && $varid===false && $prop!==false) { // if ($prop=="config") $redis->set("config",$input); // } if ($nodeid !== false && $varid === false && $prop !== false) { if ($config == null) { $config = new stdClass(); $config_changed = true; } if (!isset($config->{$nodeid})) { $config->{$nodeid} = new stdClass(); $config->{$nodeid}->nodename = ""; $config->{$nodeid}->hardware = ""; $config->{$nodeid}->firmware = ""; $config->{$nodeid}->rx = new stdClass(); $config->{$nodeid}->rx->names = array(); $config->{$nodeid}->rx->units = array(); $config->{$nodeid}->rx->processlists = array(); $config->{$nodeid}->tx = new stdClass(); $config->{$nodeid}->tx->names = array(); $config->{$nodeid}->tx->units = array(); $config->{$nodeid}->tx->processlists = array(); $config_changed = true; } if ($prop == "values") { $time = time(); $values = explode(",", $input); $nodes = json_decode($redis->get("nodes")); if ($nodes == null) { $nodes = new stdClass(); } if (!isset($nodes->{$nodeid})) { $nodes->{$nodeid} = new stdClass(); $nodes->{$nodeid}->rx = new stdClass(); $nodes->{$nodeid}->rx->time = array(); $nodes->{$nodeid}->rx->values = array(); $nodes->{$nodeid}->tx = new stdClass(); $nodes->{$nodeid}->tx->time = array(); $nodes->{$nodeid}->tx->values = array(); } if ($rxtx !== false) { $nodes->{$nodeid}->{$rxtx}->time = $time; $nodes->{$nodeid}->{$rxtx}->values = $values; $processlists = $config->{$nodeid}->{$rxtx}->processlists; $process->nodes = $nodes; for ($id = 0; $id < count($processlists); $id++) { $process->input($time, $values[$id], $processlists[$id]); } if ($rxtx == "tx") { require "Lib/phpMQTT.php"; $mqtt = new phpMQTT("127.0.0.1", 1883, "emoncmstx"); if (!$mqtt->connect()) { exit(1); } $mqtt->publish("emonhub/tx/{$nodeid}/values", implode(",", $values)); } } $redis->set("nodes", json_encode($nodes)); $result = $nodes; } else { // if ($prop=="nodename") $config->$nodeid->nodename = $input; // if ($prop=="hardware") $config->$nodeid->hardware = $input; // if ($prop=="firmware") $config->$nodeid->firmware = $input; // if ($prop=="names" && $rxtx!==false) $config->$nodeid->$rxtx->names = explode(",",$input); // if ($prop=="units" && $rxtx!==false) $config->$nodeid->$rxtx->units = explode(",",$input); $result = $config; $config_changed = true; } } if ($nodeid !== false && $varid !== false && $rxtx !== false && $prop !== false) { // if ($prop=="name") $config->$nodeid->$rxtx->names[$varid] = $input; // if ($prop=="unit") $config->$nodeid->$rxtx->units[$varid] = $input; if ($prop == "processlist") { for ($i = 0; $i <= $varid; $i++) { if (!isset($config->{$nodeid}->{$rxtx}->processlists[$i])) { $config->{$nodeid}->{$rxtx}->processlists[$i] = array(); } } $config->{$nodeid}->{$rxtx}->processlists[$varid] = json_decode($input); } $result = $config; $config_changed = true; } if ($config_changed) { $redis->set("config", json_encode($config)); $fh = fopen($emoncms_config_file, "w"); fwrite($fh, json_encode($config, JSON_PRETTY_PRINT)); fclose($fh); } } if ($route->method == 'GET') { $nodes = json_decode($redis->get("nodes")); if (!$config) { $config = new stdClass(); } if (!$nodes) { $nodes = new stdClass(); } // GET ALL // returns full list of nodes with configuration if ($nodeid === false && $varid === false && $prop === false) { foreach ($nodes as $nid => $node) { $config->{$nid}->rx->time = $nodes->{$nid}->rx->time; $config->{$nid}->rx->values = $nodes->{$nid}->rx->values; $config->{$nid}->tx->time = $nodes->{$nid}->tx->time; $config->{$nid}->tx->values = $nodes->{$nid}->tx->values; } $result = $config; } if ($nodeid !== false && isset($config->{$nodeid})) { // GET NODE // returns json object with all node properties for requested node if ($varid === false && $prop === false && $rxtx === false) { $node = $config->{$nodeid}; $node->rx->time = $nodes->{$nodeid}->rx->time; $node->rx->values = $nodes->{$nodeid}->rx->values; $node->tx->time = $nodes->{$nodeid}->tx->time; $node->tx->values = $nodes->{$nodeid}->tx->values; $result = $node; } if ($varid === false && $prop === false && $rxtx !== false) { $node = $config->{$nodeid}; $node->{$rxtx}->time = $nodes->{$nodeid}->{$rxtx}->time; $node->{$rxtx}->values = $nodes->{$nodeid}->{$rxtx}->values; if ($rxtx == "rx") { unset($node->tx); } else { unset($node->rx); } $result = $node; } // returns only requested property of requested node if ($varid === false && $prop !== false) { if ($prop == "nodename") { $result = $config->{$nodeid}->nodename; } if ($prop == "firmware") { $result = $config->{$nodeid}->firmware; } if ($prop == "hardware") { $result = $config->{$nodeid}->hardware; } if ($rxtx !== false) { if ($prop == "names") { $result = $config->{$nodeid}->{$rxtx}->names; } if ($prop == "units") { $result = $config->{$nodeid}->{$rxtx}->units; } if ($prop == "values") { $result = $nodes->{$nodeid}->{$rxtx}->values; } if ($prop == "time") { $result = $nodes->{$nodeid}->{$rxtx}->time; } } } // GET NODE:VAR if ($varid !== false && $prop === false && $rxtx !== false) { $result = array("name" => "", "value" => "", "unit" => ""); if (count($config->{$nodeid}->{$rxtx}->names) > $varid) { $result["name"] = $config->{$nodeid}->{$rxtx}->names[$varid]; } if (count($nodes->{$nodeid}->{$rxtx}->values) > $varid) { $result["value"] = (double) $nodes->{$nodeid}->{$rxtx}->values[$varid]; } if (count($config->{$nodeid}->{$rxtx}->units) > $varid) { $result["unit"] = $config->{$nodeid}->{$rxtx}->units[$varid]; } } if ($varid !== false && $prop !== false) { $result = ""; if ($prop == "name" && count($config->{$nodeid}->{$rxtx}->names) > $varid) { $result = $config->{$nodeid}->{$rxtx}->names[$varid]; } if ($prop == "unit" && count($config->{$nodeid}->{$rxtx}->units) > $varid) { $result = $config->{$nodeid}->{$rxtx}->units[$varid]; } if ($prop == "value" && count($nodes->{$nodeid}->{$rxtx}->values) > $varid) { $result = (double) $nodes->{$nodeid}->{$rxtx}->values[$varid]; } } } } if ($route->method == 'DELETE') { $nodes = json_decode($redis->get("nodes")); unset($nodes->{$nodeid}); $redis->set("nodes", json_encode($nodes)); unset($config->{$nodeid}); $redis->set("config", json_encode($config)); $fh = fopen($emoncms_config_file, "w"); fwrite($fh, json_encode($config, JSON_PRETTY_PRINT)); fclose($fh); $result = "Node {$nodeid} deleted"; } } return array('content' => $result, 'fullwidth' => true); }
<?php require "Lib/phpMQTT.php"; $mqtt = new phpMQTT("127.0.0.1", 1883, "Emoncms input pub example"); if ($mqtt->connect()) { $mqtt->publish("emoncms/input/5", "100,200,300", 0); sleep(1); $mqtt->publish("emoncms/input/10/power", 350.3, 0); sleep(1); $mqtt->publish("emoncms/input/house/power", 2500, 0); sleep(1); $mqtt->publish("emoncms/input/house/temperature", 18.2, 0); sleep(1); $m = array('apikey' => "d8e9fa2ccc5c2a9c24bc75cd8596404e", 'time' => time(), 'node' => 1, 'csv' => array(200, 300, 400)); $mqtt->publish("emoncms/input", json_encode($m), 0); sleep(1); $mqtt->close(); }
public function check_feed_event($feedid, $updatetime, $feedtime, $value, $row = NULL, $test = false) { global $user, $session, $feed; $userid = $session['userid']; $sqlFeed = "SELECT * FROM event WHERE `userid` = '{$userid}'"; if ($test) { $sqlFeed = $sqlFeed . " and id = {$feedid}"; } else { $sqlFeed = $sqlFeed . " and (`disabled` <> 1 or `disabled` IS NULL) and (eventfeed = {$feedid} or eventtype=3)"; } $result = $this->mysqli->query($sqlFeed); // check type while ($row = $result->fetch_array()) { if ($row['lasttime'] + $row['mutetime'] > time() && !$test) { continue; } if ($test) { $sendAlert = 1; } else { $sendAlert = 0; switch ($row['eventtype']) { case 0: // more than if ($value > $row['eventvalue']) { $sendAlert = 1; } break; case 1: // less than if ($value < $row['eventvalue']) { $sendAlert = 1; } break; case 2: // equal to if ($value == $row['eventvalue']) { $sendAlert = 1; } break; case 3: // inactive // not sure this can be called as no feed updated //if (((time()-$row['lasttime'])/3600)>24) {} $feedData = $feed->get($row['eventfeed']); //error_log("Feeddata: " .$feedData->time); $t = time() - strtotime($feedData['time']); //error_log("t: " .$t); if ($t > $row['eventvalue']) { $sendAlert = 1; } break; case 4: // updated $sendAlert = 1; break; case 5: // increased by $feedname = 'feed_' . $feedid; $resultprev = $this->mysqli->query("SELECT * FROM {$feedname} ORDER BY `time` DESC LIMIT 1,1"); $rowprev = $resultprev->fetch_array(); //echo "INC == ".$value." > ".$rowprev['data']."+".$row['eventvalue']; if ($value > $rowprev['data'] + $row['eventvalue']) { $sendAlert = 1; } break; case 6: // decreased by $feedname = 'feed_' . $feedid; $resultprev = $this->mysqli->query("SELECT * FROM {$feedname} ORDER BY `time` DESC LIMIT 1,1"); $rowprev = $resultprev->fetch_array(); //echo "DEC == ".$value."<". $rowprev['data']."-".$row['eventvalue']; if ($value < $rowprev['data'] - $row['eventvalue']) { $sendAlert = 1; } break; case 7: // manual update // Check if event.lasttime is less than feed.time $feedData = $feed->get($feedid); if ($feedData['time'] > $row['lasttime']) { $sendAlert = 1; } } } $feedData = $feed->get($row['eventfeed']); $message = $row['message']; $message = str_replace('{feed}', $feedData['name'], $message); $message = str_replace('{value}', $value, $message); $message = htmlspecialchars($message); if (empty($message)) { $message = "No message body"; } if ($test) { $message = 'TEST - ' . $message; } // event type if ($sendAlert == 1) { switch ($row['action']) { case 0: // email require_once realpath(dirname(__FILE__)) . '/../event/scripts/phpmailer/class.phpmailer.php'; require_once realpath(dirname(__FILE__)) . '/../event/scripts/phpmailer/class.smtp.php'; $smtp = $this->get_settings($userid); $mail = new PHPMailer(); $mail->IsSMTP(); // telling the class to use SMTP $mail->SMTPDebug = 0; // SMTP debug information (for testing) // 0 No output // 1 Commands // 2 Data and commands // 3 As 2 plus connection status // 4 Low-level data output $mail->SMTPAuth = true; // enable SMTP authentication if ($smtp['smtpport'] == 587) { $mail->SMTPSecure = "tls"; } else { if ($smtp['smtpport'] == 465) { $mail->SMTPSecure = "ssl"; } } // sets the prefix to the server $mail->Host = $smtp['smtpserver']; // sets GMAIL as the SMTP server $mail->Port = $smtp['smtpport']; // set the SMTP port for the GMAIL server $mail->Username = $smtp['smtpuser']; // GMAIL username $salt = $user->get_salt($userid); $mail->Password = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($smtp['smtppassword']), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); // GMAIL password $address = $smtp['smtpuser']; $mail->SetFrom($address, 'emoncms'); //$mail->AddReplyTo("*****@*****.**', 'First Last"); $mail->Subject = $message; //$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test $mail->MsgHTML($message); $dest = $address; if ($row['setemail'] != '') { $dest = $row['setemail']; } // Allows multiple recipients for the event email. Seperate by semi-colon ; if (strpos($dest, ';') !== false) { $addresses = explode(';', $dest); foreach ($addresses as &$addressee) { $mail->AddAddress($addressee, "emoncms"); } } else { $mail->AddAddress($dest, "emoncms"); } //$mail->AddAttachment("images/phpmailer.gif"); // attachment //$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment if (!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; error_log("Mailer Error: " . $mail->ErrorInfo); } else { echo "Message sent!"; error_log("Message sent"); } break; case 1: // set feed $setfeed = $row['setfeed']; $setvalue = $row['setvalue']; $this->redis->hMset("feed:lastvalue:{$setfeed}", array('value' => $setvalue, 'time' => $updatetime)); // $this->mysqli->query("UPDATE feeds SET value = '$setvalue', time = '$updatetime' WHERE id='$setfeed'"); break; case 2: // call url $explodedUrl = preg_split('/[?]+/', $row['callcurl'], -1); if (count($explodedUrl) > 1) { $explodedUrl[1] = str_replace(' ', '%20', str_replace('{value}', $value, str_replace('{feed}', $feedData->name, $explodedUrl[1]))); } $ch = curl_init(); $body = $explodedUrl[0] . '?' . $explodedUrl[1]; // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, $body); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FRESH_CONNECT, true); curl_setopt($ch, CURLOPT_TIMEOUT, 1); // grab URL and pass it to the browser if (curl_exec($ch) === false) { error_log("Curl Error:" . curl_error($ch)); } // close cURL resource, and free up system resources curl_close($ch); error_log("Curl Log:" . $body); break; case 3: // Twitter require_once realpath(dirname(__FILE__)) . '/../event/scripts/twitter/twitter-api-php/TwitterAPIExchange.php'; $twitter = $this->get_user_twitter($userid); // Twitter disallow duplicate tweets within an unspecified and variable time per account // so add the feed time to make each tweet unique. $message = $message . ' at ' . date("H:i:s", $feedtime); // Set the OAauth values $settings = array('oauth_access_token' => $twitter['usertoken'], 'oauth_access_token_secret' => $twitter['usersecret'], 'consumer_key' => $twitter['consumerkey'], 'consumer_secret' => $twitter['consumersecret']); // Make the API call $url = 'https://api.twitter.com/1.1/statuses/update.json'; $requestMethod = 'POST'; $postfields = array('status' => $message); $tweet = new TwitterAPIExchange($settings); echo $tweet->buildOauth($url, $requestMethod)->setPostfields($postfields)->performRequest(); break; case 4: // Prowl require_once realpath(dirname(__FILE__)) . '/scripts/prowlphp/ProwlConnector.class.php'; require_once realpath(dirname(__FILE__)) . '/scripts/prowlphp/ProwlMessage.class.php'; require_once realpath(dirname(__FILE__)) . '/scripts/prowlphp/ProwlResponse.class.php'; $prowl = $this->get_user_prowl($userid); $oProwl = new ProwlConnector(); $oMsg = new ProwlMessage(); $oProwl->setIsPostRequest(true); $oMsg->setPriority($row['priority']); $oMsg->addApiKey($prowl['prowlkey']); $oMsg->setEvent($message); // These are optional: $message = 'event at ' . date("Y-m-d H:i:s", time()); $oMsg->setDescription($message); $oMsg->setApplication('emoncms'); $oResponse = $oProwl->push($oMsg); if ($oResponse->isError()) { error_log("Prowl error:" . $oResponse->getErrorAsString()); } break; case 5: // NMA require_once realpath(dirname(__FILE__)) . '/scripts/nma/nmaApi.class.php'; $nmakey = $this->get_user_nma($userid); $nma = new nmaApi(array('apikey' => $nmakey['nmakey'])); $priority = $row['priority']; if ($nma->verify()) { $nma->notify('EmonCMS ' . $message, 'EmonCMS', $message, $priority); } break; case 6: // MQTT require_once realpath(dirname(__FILE__)) . '/scripts/mqtt/phpMQTT.php'; $mqttSettings = $this->get_user_mqtt($userid); $salt = $user->get_salt($userid); $mqtttopic = $row['mqtttopic']; $mqtttopic = str_replace('{feed}', $feedData['name'], $mqtttopic); $mqtttopic = str_replace('{value}', $value, $mqtttopic); $mqtttopic = htmlspecialchars($mqtttopic); $mqttqos = $row['mqttqos']; if (empty($mqttqos)) { $mqttqos = 0; } // setup connection $mqtt = new phpMQTT($mqttSettings['mqttbrokerip'], $mqttSettings['mqttbrokerport'], "emoncms"); if (empty($mqttSettings['mqttusername'])) { $mqttConnected = $mqtt->connect(); } else { $mqttusername = $mqttSettings['mqttusername']; $mqttpassword = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, base64_decode($mqttSettings['mqttpassword']), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))); $mqttConnected = $mqtt->connect(false, NULL, $mqttusername, $mqttpassword); } if ($mqttConnected) { $mqtt->publish($mqtttopic, $message, $mqttqos); } else { error_log("MQTT connection failed"); } $mqtt->close(); break; } // update the lasttime called if (!$test) { $this->mysqli->query("UPDATE event SET lasttime = '" . time() . "' WHERE id='" . $row['id'] . "'"); } } } }
<?php require "../phpMQTT.php"; $mqtt = new phpMQTT("example.com", 1883, "phpMQTT Pub Example"); //Change client name to something unique if ($mqtt->connect()) { $mqtt->publish("bluerhinos/phpMQTT/examples/publishtest", "Hello World! at " . date("r"), 0); $mqtt->close(); } #subcribe.php /* require("../phpMQTT.php"); $mqtt = new phpMQTT("example.com", 1883, "phpMQTT Sub Example"); //Change client name to something unique if(!$mqtt->connect()){ exit(1); } $topics['ferries/IOW/#'] = array("qos"=>0, "function"=>"procmsg"); $mqtt->subscribe($topics,0); while($mqtt->proc()){ } $mqtt->close();
<?php require "Lib/phpMQTT.php"; $mqtt = new phpMQTT("127.0.0.1", 1883, "Emoncms feed subscriber"); if (!$mqtt->connect()) { exit(1); } $topics["emoncms/#"] = array("qos" => 0, "function" => "procmsg"); $mqtt->subscribe($topics, 0); while ($mqtt->proc()) { } $mqtt->close(); function procmsg($topic, $value) { $time = time(); print $topic . " " . $value . "\n"; }
$type = (string) $input->type; include 'conn.php'; if ("switch" == $type) { $value = $input->value; $device_value = "{\"switch\":" . (string) $value . "}"; $mqtt_message = json_encode(json_decode($device_value, true), JSON_NUMERIC_CHECK); } elseif ("step" == $type) { $switch = (string) $input->switch; $controller = (string) $input->controller; $value = '{"switch":' . $switch . ',"controller":' . $controller . '}'; $mqtt_message = json_encode(json_decode($value, true), JSON_NUMERIC_CHECK); } $sql = "update devices set value='{$value}' where id='{$id}'"; $result = @mysql_query($sql); require "public/phpMQTT.php"; $mqtt = new phpMQTT("127.0.0.1", 1883, "phpMQTT"); //Change client name to something unique if ($mqtt->connect()) { $mqtt->publish("d" . $id, $mqtt_message, 0); $mqtt->close(); } if ($result) { echo json_encode(array('success' => true)); } else { echo json_encode(array('success' => false)); } }); /*************** User **********************/ $app->get('/userall', function () use($app) { $username = htmlspecialchars($_GET['username']); // $password = $_POST['pwd'];
die('Check log\\n'); } if (!empty($redis_server['prefix'])) { $redis->setOption(Redis::OPT_PREFIX, $redis_server['prefix']); } if (!empty($redis_server['auth'])) { if (!$redis->auth($redis_server['auth'])) { $log->error("Could not connect to redis at " . $redis_server['host'] . ", autentication failed"); die('Check log\\n'); } } } else { $redis = false; } require "Lib/phpMQTT.php"; $mqtt = new phpMQTT($mqtt_server['host'], $mqtt_server['port'], "Emoncms input subscriber"); require "Modules/user/user_model.php"; $user = new User($mysqli, $redis, null); require_once "Modules/feed/feed_model.php"; $feed = new Feed($mysqli, $redis, $feed_settings); require_once "Modules/input/input_model.php"; $input = new Input($mysqli, $redis, $feed); require_once "Modules/process/process_model.php"; $process = new Process($mysqli, $input, $feed, $user->get_timezone($mqttsettings['userid'])); if (!$mqtt->connect(true, NULL, $mqtt_server['user'], $mqtt_server['password'])) { $log->error("Cannot connect to MQTT Server"); die('Check log\\n'); } $topic = $mqttsettings['basetopic'] . "/#"; echo "Subscribing to: " . $topic . "\n"; $topics[$topic] = array("qos" => 0, "function" => "procmsg");