function ProcessRequest()
 {
     require_once GTFW_APP_DIR . 'module/gtfw_menu/response/Process.proc.class.php';
     $Proc = new Process();
     $post = $_POST->AsArray();
     $result = $Proc->input();
     if ($result == true) {
         Messenger::Instance()->Send('gtfw_menu', 'menu', 'view', 'html', array(NULL, 'Penambahan data berhasil', 'notebox-done'), Messenger::NextRequest);
         $redirect = Dispatcher::Instance()->GetUrl('gtfw_menu', 'menu', 'view', 'html') . '&display';
     } else {
         Messenger::Instance()->Send('gtfw_menu', 'input', 'view', 'html', array($post, implode('<br/>', $Proc->err_msg), 'notebox-warning'), Messenger::NextRequest);
         $redirect = Dispatcher::Instance()->GetUrl('gtfw_menu', 'add', 'view', 'html');
     }
     $this->RedirectTo($redirect);
 }
function input_controller()
{
    //return array('content'=>"ok");
    global $mysqli, $redis, $user, $session, $route, $max_node_id_limit, $feed_settings;
    // There are no actions in the input module that can be performed with less than write privileges
    if (!$session['write']) {
        return array('content' => false);
    }
    global $feed, $timestore_adminkey;
    $result = false;
    include "Modules/feed/feed_model.php";
    $feed = new Feed($mysqli, $redis, $feed_settings);
    require "Modules/input/input_model.php";
    // 295
    $input = new Input($mysqli, $redis, $feed);
    require "Modules/input/process_model.php";
    // 886
    $process = new Process($mysqli, $input, $feed);
    $process->set_timezone_offset($user->get_timezone($session['userid']));
    if ($route->format == 'html') {
        if ($route->action == 'api') {
            $result = view("Modules/input/Views/input_api.php", array());
        }
        if ($route->action == 'view') {
            $result = view("Modules/input/Views/input_view.php", array());
        }
    }
    if ($route->format == 'json') {
        /*
        
        input/bulk.json?data=[[0,16,1137],[2,17,1437,3164],[4,19,1412,3077]]
        
        The first number of each node is the time offset (see below).
        
        The second number is the node id, this is the unique identifer for the wireless node.
        
        All the numbers after the first two are data values. The first node here (node 16) has only one data value: 1137.
        
        Optional offset and time parameters allow the sender to set the time
        reference for the packets.
        If none is specified, it is assumed that the last packet just arrived.
        The time for the other packets is then calculated accordingly.
        
        offset=-10 means the time of each packet is relative to [now -10 s].
        time=1387730127 means the time of each packet is relative to 1387730127
        (number of seconds since 1970-01-01 00:00:00 UTC)
        
        Examples:
        
        // legacy mode: 4 is 0, 2 is -2 and 0 is -4 seconds to now.
          input/bulk.json?data=[[0,16,1137],[2,17,1437,3164],[4,19,1412,3077]]
        // offset mode: -6 is -16 seconds to now.
          input/bulk.json?data=[[-10,16,1137],[-8,17,1437,3164],[-6,19,1412,3077]]&offset=-10
        // time mode: -6 is 1387730121
          input/bulk.json?data=[[-10,16,1137],[-8,17,1437,3164],[-6,19,1412,3077]]&time=1387730127
        // sentat (sent at) mode:
          input/bulk.json?data=[[520,16,1137],[530,17,1437,3164],[535,19,1412,3077]]&offset=543
        
        See pull request for full discussion:
        https://github.com/emoncms/emoncms/pull/118
        */
        if ($route->action == 'bulk') {
            $valid = true;
            if (!isset($_GET['data']) && isset($_POST['data'])) {
                $data = json_decode(post('data'));
            } else {
                $data = json_decode(get('data'));
            }
            $userid = $session['userid'];
            $dbinputs = $input->get_inputs($userid);
            $len = count($data);
            if ($len > 0) {
                if (isset($data[$len - 1][0])) {
                    // Sent at mode: input/bulk.json?data=[[45,16,1137],[50,17,1437,3164],[55,19,1412,3077]]&sentat=60
                    if (isset($_GET['sentat'])) {
                        $time_ref = time() - (int) $_GET['sentat'];
                    } elseif (isset($_POST['sentat'])) {
                        $time_ref = time() - (int) $_POST['sentat'];
                    } elseif (isset($_GET['offset'])) {
                        $time_ref = time() - (int) $_GET['offset'];
                    } elseif (isset($_POST['offset'])) {
                        $time_ref = time() - (int) $_POST['offset'];
                    } elseif (isset($_GET['time'])) {
                        $time_ref = (int) $_GET['time'];
                    } elseif (isset($_POST['time'])) {
                        $time_ref = (int) $_POST['time'];
                    } else {
                        $time_ref = time() - (int) $data[$len - 1][0];
                    }
                    foreach ($data as $item) {
                        if (count($item) > 2) {
                            // check for correct time format
                            $itemtime = (int) $item[0];
                            $time = $time_ref + (int) $itemtime;
                            $nodeid = $item[1];
                            $inputs = array();
                            $name = 1;
                            for ($i = 2; $i < count($item); $i++) {
                                $value = (double) $item[$i];
                                $inputs[$name] = $value;
                                $name++;
                            }
                            $tmp = array();
                            foreach ($inputs as $name => $value) {
                                if ($input->check_node_id_valid($nodeid)) {
                                    if (!isset($dbinputs[$nodeid][$name])) {
                                        $inputid = $input->create_input($userid, $nodeid, $name);
                                        $dbinputs[$nodeid][$name] = true;
                                        $dbinputs[$nodeid][$name] = array('id' => $inputid, 'processList' => '');
                                        $input->set_timevalue($dbinputs[$nodeid][$name]['id'], $time, $value);
                                    } else {
                                        $inputid = $dbinputs[$nodeid][$name]['id'];
                                        $input->set_timevalue($dbinputs[$nodeid][$name]['id'], $time, $value);
                                        if ($dbinputs[$nodeid][$name]['processList']) {
                                            $tmp[] = array('value' => $value, 'processList' => $dbinputs[$nodeid][$name]['processList']);
                                        }
                                    }
                                } else {
                                    $valid = false;
                                    $error = "NodeID must be a positive integer between 0 and " . $max_node_id_limit . ", nodeid given was out of range";
                                }
                            }
                            foreach ($tmp as $i) {
                                $process->input($time, $i['value'], $i['processList']);
                            }
                        } else {
                            $valid = false;
                            $error = "Format error, bulk item needs at least 3 values";
                        }
                    }
                } else {
                    $valid = false;
                    $error = "Format error, last item in bulk data does not contain any data";
                }
            } else {
                $valid = false;
                $error = "Format error, json string supplied is not valid";
            }
            if ($valid) {
                $result = 'ok';
            } else {
                $result = "Error: {$error}\n";
            }
        }
        // input/post.json?node=10&json={power1:100,power2:200,power3:300}
        // input/post.json?node=10&csv=100,200,300
        if ($route->action == 'post') {
            $valid = true;
            $error = "";
            $nodeid = (int) get('node');
            $error = " old" . $max_node_id_limit;
            if (!isset($max_node_id_limit)) {
                $max_node_id_limit = 32;
            }
            $error .= " new" . $max_node_id_limit;
            if (!$input->check_node_id_valid($nodeid)) {
                $valid = false;
                $error = "NodeID must be a positive integer between 0 and " . $max_node_id_limit . ", nodeid given was out of range";
            }
            if (!$valid) {
                return array('content' => "{$error}");
            }
            $nodeid = (int) $nodeid;
            if (isset($_GET['time'])) {
                $time = (int) $_GET['time'];
            } else {
                $time = time();
            }
            $data = array();
            $datain = false;
            // code below processes input regardless of json or csv type
            if (isset($_GET['json'])) {
                $datain = get('json');
            }
            if (isset($_GET['csv'])) {
                $datain = get('csv');
            }
            if (isset($_GET['data'])) {
                $datain = get('data');
            }
            if (isset($_POST['data'])) {
                $datain = post('data');
            }
            if ($datain != "") {
                $json = preg_replace('/[^\\w\\s-.:,]/', '', $datain);
                $datapairs = explode(',', $json);
                $csvi = 0;
                for ($i = 0; $i < count($datapairs); $i++) {
                    $keyvalue = explode(':', $datapairs[$i]);
                    if (isset($keyvalue[1])) {
                        if ($keyvalue[0] == '') {
                            $valid = false;
                            $error = "Format error, json key missing or invalid character";
                        }
                        if (!is_numeric($keyvalue[1])) {
                            $valid = false;
                            $error = "Format error, json value is not numeric";
                        }
                        $data[$keyvalue[0]] = (double) $keyvalue[1];
                    } else {
                        if (!is_numeric($keyvalue[0])) {
                            $valid = false;
                            $error = "Format error: csv value is not numeric";
                        }
                        $data[$csvi + 1] = (double) $keyvalue[0];
                        $csvi++;
                    }
                }
                $userid = $session['userid'];
                $dbinputs = $input->get_inputs($userid);
                $tmp = array();
                foreach ($data as $name => $value) {
                    if (!isset($dbinputs[$nodeid][$name])) {
                        $inputid = $input->create_input($userid, $nodeid, $name);
                        $dbinputs[$nodeid][$name] = true;
                        $dbinputs[$nodeid][$name] = array('id' => $inputid);
                        $input->set_timevalue($dbinputs[$nodeid][$name]['id'], $time, $value);
                    } else {
                        $inputid = $dbinputs[$nodeid][$name]['id'];
                        $input->set_timevalue($dbinputs[$nodeid][$name]['id'], $time, $value);
                        if ($dbinputs[$nodeid][$name]['processList']) {
                            $tmp[] = array('value' => $value, 'processList' => $dbinputs[$nodeid][$name]['processList']);
                        }
                    }
                }
                foreach ($tmp as $i) {
                    $process->input($time, $i['value'], $i['processList']);
                }
            } else {
                $valid = false;
                $error = "Request contains no data via csv, json or data tag";
            }
            if ($valid) {
                $result = 'ok';
            } else {
                $result = "Error: {$error}\n";
            }
        }
        if ($route->action == "clean") {
            $result = $input->clean($session['userid']);
        }
        if ($route->action == "list") {
            $result = $input->getlist($session['userid']);
        }
        if ($route->action == "getinputs") {
            $result = $input->get_inputs($session['userid']);
        }
        if ($route->action == "getallprocesses") {
            $result = $process->get_process_list();
        }
        if (isset($_GET['inputid']) && $input->belongs_to_user($session['userid'], get("inputid"))) {
            if ($route->action == "delete") {
                $result = $input->delete($session['userid'], get("inputid"));
            }
            if ($route->action == 'set') {
                $result = $input->set_fields(get('inputid'), get('fields'));
            }
            if ($route->action == "process") {
                if ($route->subaction == "add") {
                    $result = $input->add_process($process, $session['userid'], get('inputid'), get('processid'), get('arg'), get('newfeedname'), get('newfeedinterval'), get('engine'));
                }
                if ($route->subaction == "list") {
                    $result = $input->get_processlist(get("inputid"));
                }
                if ($route->subaction == "delete") {
                    $result = $input->delete_process(get("inputid"), get('processid'));
                }
                if ($route->subaction == "move") {
                    $result = $input->move_process(get("inputid"), get('processid'), get('moveby'));
                }
                if ($route->subaction == "reset") {
                    $result = $input->reset_process(get("inputid"));
                }
            }
        }
    }
    return array('content' => $result);
}
function wattsup_controller()
{
    global $mysqli, $redis, $user, $session, $route, $feed_settings;
    // First up, a little hack.
    // We need to include an API key with our POST data from the Watts Up?,
    // but the stupid thing limits how long our POST location string can be.
    // SO, we put the API key in the user agent string, cause why not.
    $apikey = $_SERVER["HTTP_USER_AGENT"];
    $session = $user->apikey_session($apikey);
    if (empty($session)) {
        header($_SERVER["SERVER_PROTOCOL"] . " 401 Unauthorized");
        header('WWW-Authenticate: Bearer realm="API KEY", error="invalid_apikey", error_description="Invalid API key"');
        print "Invalid API key";
        $log = new EmonLogger(__FILE__);
        $log->error("Invalid API key '" . $apikey . "'");
        exit;
    }
    // There are no actions in the input module that can be performed with less than write privileges
    if (!$session['write']) {
        return array('content' => false);
    }
    $result = false;
    // Need to get correct files so that we can make inputs
    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($session['userid']));
    // Process /wattsup/post.text messages from Watts Up? .net
    if ($route->action == 'post' && $route->format == 'text') {
        // This looks like a correctly configured Watts Up? .net POST
        $valid = true;
        $error = '';
        $userid = $session['userid'];
        $dbinputs = $input->get_inputs($userid);
        // id is set to the Watts Up? device ID
        $nodeid = preg_replace('/[^\\p{N}\\p{L}_\\s-.]/u', '', post('id'));
        // Make sure we can do this. Copied from input_controller.php
        $validate_access = $input->validate_access($dbinputs, $nodeid);
        if (!$validate_access['success']) {
            $valid = false;
            $error = $validate_access['message'];
        } else {
            // Insert this record into the emoncms format
            $time = time();
            // Array to store the relevant fields in
            $data = array();
            $watts = post('w');
            $volts = post('v');
            $amps = post('a');
            $watth = post('wh');
            $maxwatts = post('wmx');
            $maxvolts = post('vmx');
            $maxamps = post('amx');
            $minwatts = post('wmi');
            $minvolts = post('vmi');
            $minamps = post('ami');
            $pf = post('pf');
            $pcy = post('pcy');
            $freq = post('frq');
            $voltamps = post('va');
            # Only include fields we actually got
            if (is_numeric($watts)) {
                $data['watts'] = $watts / 10;
            }
            if (is_numeric($volts)) {
                $data['volts'] = $volts / 10;
            }
            if (is_numeric($amps)) {
                $data['amps'] = $amps / 1000;
            }
            if (is_numeric($watth)) {
                $data['watt_hours'] = $watth / 1000;
            }
            if (is_numeric($maxwatts)) {
                $data['max_watts'] = $maxwatts / 10;
            }
            if (is_numeric($maxvolts)) {
                $data['max_volts'] = $maxvolts / 10;
            }
            if (is_numeric($maxamps)) {
                $data['max_amps'] = $maxamps / 1000;
            }
            if (is_numeric($minwatts)) {
                $data['min_watts'] = $minwatts / 10;
            }
            if (is_numeric($minvolts)) {
                $data['min_volts'] = $minvolts / 10;
            }
            if (is_numeric($minamps)) {
                $data['min_amps'] = $minamps / 1000;
            }
            if (is_numeric($pf)) {
                $data['power_factor'] = $pf;
            }
            if (is_numeric($pcy)) {
                $data['power_cycle'] = $pcy;
            }
            if (is_numeric($freq)) {
                $data['freq'] = $freq / 10;
            }
            if (is_numeric($voltamps)) {
                $data['volt_amps'] = $voltamps / 10;
            }
            // Iterate all new data items to insert
            $tmp = array();
            foreach ($data as $name => $value) {
                // Check if this is an existing field in this node or not
                if (!isset($dbinputs[$nodeid][$name])) {
                    // New field.
                    $inputid = $input->create_input($userid, $nodeid, $name);
                    $dbinputs[$nodeid][$name] = true;
                    $dbinputs[$nodeid][$name] = array('id' => $inputid, 'processList' => '');
                    $input->set_timevalue($dbinputs[$nodeid][$name]['id'], $time, $value);
                } else {
                    // Existing field, just insert
                    $input->set_timevalue($dbinputs[$nodeid][$name]['id'], $time, $value);
                    // If there are processes listening to this field, we need
                    // to pass the data to those as well
                    if ($dbinputs[$nodeid][$name]['processList']) {
                        $tmp[] = array('value' => $value, 'processList' => $dbinputs[$nodeid][$name]['processList'], 'opt' => array('sourcetype' => "WATTSUP", 'sourceid' => $dbinputs[$nodeid][$name]['id']));
                    }
                }
            }
            // Actually insert all of the data to the process
            foreach ($tmp as $i) {
                $process->input($time, $i['value'], $i['processList'], $i['opt']);
            }
        }
        if ($valid) {
            $result = 'ok';
        } else {
            $result = "Error: {$error}\n";
        }
    }
    return array('content' => $result);
}
        $time = $packet->time;
        $nodeid = $packet->nodeid;
        $data = $packet->data;
        // Load current user input meta data
        // It would be good to avoid repeated calls to this
        $dbinputs = $input->get_inputs($userid);
        if (!isset($dbinputs[$nodeid]) && count($dbinputs) >= $max_node_id_limit) {
            $log->error("Reached the maximal allowed number of diferent NodeIds, limit is {$max_node_id_limit}. Node '{$nodeid}' was ignored.");
        } else {
            $tmp = array();
            foreach ($data as $name => $value) {
                if (!isset($dbinputs[$nodeid][$name])) {
                    $inputid = $input->create_input($userid, $nodeid, $name);
                    $dbinputs[$nodeid][$name] = true;
                    $dbinputs[$nodeid][$name] = array('id' => $inputid, 'processList' => '');
                    $input->set_timevalue($dbinputs[$nodeid][$name]['id'], $time, $value);
                } else {
                    $inputid = $dbinputs[$nodeid][$name]['id'];
                    $input->set_timevalue($dbinputs[$nodeid][$name]['id'], $time, $value);
                    if ($dbinputs[$nodeid][$name]['processList']) {
                        $tmp[] = array('value' => $value, 'processList' => $dbinputs[$nodeid][$name]['processList']);
                    }
                }
            }
            foreach ($tmp as $i) {
                $process->input($time, $i['value'], $i['processList']);
            }
        }
    }
    usleep($usleep);
}
Exemple #5
0
 public function get_data($feedid, $start, $end, $interval, $skipmissing, $limitinterval)
 {
     $feedid = intval($feedid);
     $processList = $this->feed->get_processlist($feedid);
     if ($processList == '' || $processList == null) {
         return false;
     }
     $start = round($start / 1000);
     $end = round($end / 1000);
     $interval = intval($interval);
     // time gap in seconds
     if ($interval < 1) {
         $interval = 1;
     }
     $dp = ceil(($end - $start) / $interval);
     // datapoints for desied range with set interval time gap
     $end = $start + $dp * $interval;
     if ($dp < 1) {
         return false;
     }
     // Check if datatype is daily so that select over range is used rather than skip select approach
     static $feed_datatype_cache = array();
     // Array to hold the cache
     if (isset($feed_datatype_cache[$feedid])) {
         $datatype = $feed_datatype_cache[$feedid];
         // Retrieve from static cache
     } else {
         $result = $this->mysqli->query("SELECT datatype FROM feeds WHERE `id` = '{$feedid}'");
         $row = $result->fetch_array();
         $datatype = $row['datatype'];
         $feed_datatype_cache[$feedid] = $datatype;
         // Cache it
     }
     if ($datatype == 2) {
         $dp = 0;
     }
     // daily
     $this->log->info("get_data() feedid={$feedid} start={$start} end={$end} int={$interval} sk={$skipmissing} li={$limitinterval}");
     $data = array();
     $dataValue = null;
     // Lets instantiate a new class of process so we can run many proceses recursively without interference
     global $session, $user;
     require_once "Modules/process/process_model.php";
     $process = new Process($this->mysqli, $this->input, $this->feed, $user->get_timezone($session['userid']));
     if ($dp > 0) {
         $range = $end - $start;
         // windows duration in seconds
         $td = $range / $dp;
         // time duration for each datapoint
         $t = $start;
         $tb = 0;
         // time between t and tb
         for ($i = 0; $i < $dp; $i++) {
             $tb = $start + intval(($i + 1) * $td);
             //next end time
             $opt_timearray = array('start' => $t, 'end' => $tb, 'interval' => $interval);
             $dataValue = $process->input($t, $dataValue, $processList, $opt_timearray);
             // execute processlist
             if ($dataValue != NULL || $skipmissing === 0) {
                 // Remove this to show white space gaps in graph
                 $time = $t * 1000;
                 if ($dataValue !== null) {
                     $dataValue = (double) $dataValue;
                 }
                 $data[] = array($time, $dataValue);
             }
             $t = $tb;
             // next start time
         }
     } else {
         //daily virtual feed
         $startslot = $process->process__getstartday($start);
         // start of day for user timezone
         $endslot = $process->process__getstartday($end);
         // end of day for user timezone
         if ($endslot < $startslot) {
             $endslot = $endslot + 86400;
         }
         // one day range
         while ($startslot < $endslot) {
             $opt_timearray = array('start' => $startslot, 'end' => $startslot + 86400, 'interval' => $interval);
             $dataValue = $process->input($startslot, $dataValue, $processList, $opt_timearray);
             // execute processlist
             if ($dataValue != NULL || $skipmissing === 0) {
                 // Remove this to show white space gaps in graph
                 $time = $startslot * 1000;
                 if ($dataValue !== null) {
                     $dataValue = (double) $dataValue;
                 }
                 $data[] = array($time, $dataValue);
             }
             $startslot += 86400;
             // inc a day
         }
     }
     return $data;
 }
Exemple #6
0
function ted_controller()
{
    global $mysqli, $redis, $user, $session, $route, $feed_settings;
    // Start by filtering by request path
    if ($route->action == 'post' && $route->format == 'text') {
        // Need to get the POST body
        $post = file_get_contents("php://input");
        // Look for an activation POST
        if (startsWith($post, '<ted5000Activation>')) {
            // Get the gateway and unique values
            $gateway = extract_value($post, '<Gateway>', '</Gateway>');
            $unique = extract_value($post, '<Unique>', '</Unique>');
            // Make sure this is permitted and that the user set up the device
            // in emoncms.
            $session = check_device_key($unique);
            // Need to get values for the response
            if (isset($_SERVER['HTTP_X_FORWARDED_SERVER'])) {
                $server = server('HTTP_X_FORWARDED_SERVER');
            } else {
                $server = server('HTTP_HOST');
            }
            $url = server('SCRIPT_NAME');
            $result = '<ted5000ActivationResponse>' . "<PostServer>{$server}</PostServer>" . '<UseSSL>F</UseSSL>' . '<PostPort>80</PostPort>' . '<PostURL>/ted/post.text</PostURL>' . "<AuthToken>{$unique}</AuthToken>" . '<PostRate>2</PostRate>' . '<HighPrec>T</HighPrec>' . '</ted5000ActivationResponse>';
        } else {
            if (startsWith($post, '<ted5000 ')) {
                // Got data POST
                $nodeid = extract_value($post, 'GWID="', '"');
                $unique = extract_value($post, 'auth="', '"');
                $session = check_device_key($unique);
                $userid = $session['userid'];
                // Setup variable we need to insert data
                // Need to get correct files so that we can make inputs
                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($userid));
                // Fetch the known inputs from the database
                $dbinputs = $input->get_inputs($userid);
                // Make sure we can save this data.
                if ($nodeid != $session['nodeid']) {
                    header($_SERVER["SERVER_PROTOCOL"] . " 401 Unauthorized");
                    header('WWW-Authenticate: Bearer realm="Device KEY", error="invalid_nodeid", error_description="Invalid node"');
                    print "Invalid node({$nodeid}) for that device key({$unique})";
                    exit;
                }
                // Get the MTU values from the POST data
                $values = extract_mtu($post);
                $time = time();
                // Actually insert data
                $tmp = array();
                foreach ($values as $name => $value) {
                    // Check if this is an existing field in this node or not
                    if (!isset($dbinputs[$nodeid][$name])) {
                        // New field.
                        $inputid = $input->create_input($userid, $nodeid, $name);
                        $dbinputs[$nodeid][$name] = true;
                        $dbinputs[$nodeid][$name] = array('id' => $inputid, 'processList' => '');
                        $input->set_timevalue($dbinputs[$nodeid][$name]['id'], $time, $value);
                    } else {
                        // Existing field, just insert
                        $input->set_timevalue($dbinputs[$nodeid][$name]['id'], $time, $value);
                        // If there are processes listening to this field, we need
                        // to pass the data to those as well
                        if ($dbinputs[$nodeid][$name]['processList']) {
                            $tmp[] = array('value' => $value, 'processList' => $dbinputs[$nodeid][$name]['processList'], 'opt' => array('sourcetype' => "WATTSUP", 'sourceid' => $dbinputs[$nodeid][$name]['id']));
                        }
                    }
                }
                // Actually insert all of the data to the process
                foreach ($tmp as $i) {
                    $process->input($time, $i['value'], $i['processList'], $i['opt']);
                }
                $result = 'ok';
            } else {
                $result = 'Unknown';
            }
        }
    }
    return array('content' => $result);
}
Exemple #7
0
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_once 'env.php';
$idx = Process::input('-i');
$all = Process::input('-a');
if (!flock($_lock = fopen(basename(__FILE__) . ".{$idx}.lck", 'w'), LOCK_EX | LOCK_NB)) {
    exit(date('c') . ' another proccess is running' . PHP_EOL);
}
set_time_limit(0);
$process = new Process_SendRoomStatMail($idx, $all);
$process();
// End of file : sendRoomStatMail_per_day.php