Code Samples


Some code examples showing how to use the Solar Forecast webservice from some common programming languages. It should be straight-forward to adapt these examples to other programming languages.

Note that the Python examples use the popular Requests package, which is not part of the standard library but can usually be installed without any problems (type pip install requests in a shell window). The PHP examples are pure PHP, which makes them look a bit cumbersome. Check the Guzzle library for a more comfortable way of doing HTTP requests.

Add a site

Python

import requests
mdx_key = 'AAABBBCCCDDDEEEFFFGGGHHH11122233'
# replace with your KEY!
mdx_url = ('https://mdx.meteotest.ch/api_v1?key={key}&service=solarforecast'
           '&action=siteadd&latitude=47.2&longitude=7.2&inclination=30'
           '&azimuth=180&format=json'.format(key=mdx_key))

r = requests.get(mdx_url)
result = r.json()
# if it worked, variable 'result' contains details of
# created site. Otherwise 'result' contains an
# error message.

if r.status_code == 200:
  print("It worked!")
else:
  print("An error occurred:")
  # let's check what the problem is...
  print(result)
                

Reading forecast data

Python

import requests
mdx_key = 'AAABBBCCCDDDEEEFFFGGGHHH11122233'
# replace with your KEY!
mdx_url = ('https://mdx.meteotest.ch/api_v1?key={key}&service=solarforecast'
           '&action=getforecast&format=json'.format(key=mdx_key)

r = requests.get(mdx_url)
result = r.json()

if r.status_code == 200:
  print("forecast data:")
  print(result)
else:
  print("An error occurred:")
  # let's check what the problem is...
  print(result)

Sending real-time measurements (Kalman filter option)

Sending real-time measurements from your sites is a bit special in that it must be done through an HTTP POST request, as opposed to GET requests that are used for the other features. The data itself must be either a valid JSON or a valid CSV string. The following code sends some measurements as a JSON string. Note that date/time (in UTC) must be provided in format YYYY-mm-dd HH:MM:SS. Example: 2014-06-25 14:10:00.

Make sure that your date/time values mark the end of a time interval and that measurement values represent the arithmetic mean over an interval. See the documentation for details.

Python

import requests

def upload_measurements(mdx_key, data):
  post_params = {
    'key': mdx_key,
    'service': 'solarforecast',
    'action': 'add_measurements',
    'format': 'json',
    'measurements': data
  }
  mdx_url = 'https://mdx.meteotest.ch/api_v1'
  r = requests.post(mdx_url, data=post_params)
  if r.status_code == 200:
    return
  else:
    r_json = r.json()
    raise Exception('{0} (http status {1})'.format(r_json.error, r.status_code))

# replace "123" with a valid site ID!
data = """
  {
    "123": {
      "2014-06-17 05:00:00": {
        "tt": 15.8,
        "gh": 58,
        "gk": 70,
      },
      "2014-06-17 06:00:00": {
        "tt": 17.7,
        "gh": 219,
        "gk": 369,
      }
    }
  }"""
try: upload_measurements(mdx_key='INSERT_YOUR_MDX_KEY_HERE', data=data)
except Exception as e:
  print(e)
else:
  print("Successfully uploaded measurements.")

PHP

function upload_measurements($mdx_key, $data) {
    $mdx_url = 'https://mdx.meteotest.ch/api_v1';
    $post_params = array('key' => $mdx_key, 'service' => 'solarforecast',
      'action' => 'add_measurements', 'format' => 'json',
      'measurements' => $data);
    $params_str = '';
    foreach($post_params as $key => $value) {
      $params_str .= $key . '=' . $value . '&';
    }
    rtrim($params_str, '&'); # remove trailing '&'

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $mdx_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    # write the response into a variable
    curl_setopt($ch, CURLOPT_POST, count($params));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params_str);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
    curl_setopt($ch, CURLOPT_TIMEOUT, 180);
    $result = curl_exec($ch);

    if ($result === false) {
      $err = curl_error($ch);
      curl_close($ch);
      throw new Exception($err);
    } else {
      $http_statuscode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      if ($http_statuscode == 200) {
        curl_close($ch);
        return;
      } else {
        $r = json_decode($result);
        curl_close($ch);
        throw new Exception("$r->error (http status $http_statuscode)");
      }
    }
}

# replace "123" with a valid site ID!
data = ' 
{
  "123": {
    "2014-06-17 05:00:00": {
      "tt": 15.8,
      "gh": 58,
      "gk": 70,
    },
    "2014-06-17 06:00:00": {
      "tt": 17.7,
      "gh": 219,
      "gk": 369,
    }
  }
}';
$error = False;
try {
    upload_measurements('INSERT_YOUR_MDX_KEY_HERE', $data);
  } catch (Exception $e) {
    printf("An error occurred: %s\n", $e->getMessage());
    $error = True;
  }
  if (! $error) {
    print("Measurements successfully uploaded.\n");
}

As an alternative to JSON, you can send data as comma separated values (CSV). Columns must be named SITE_ID-param, where SITE_ID is an ID of one of your registered sites and param is a parameter. In the example below, replace 123 with a valid site ID.

# replace '123' with valid site ID!
data = """
  datetime;123-tt;123-gh;123-gk;
  "2014-06-30 14:00:00";11.3;669;76
  "2014-06-30 15:00:00";12.6;518;64
  "2014-06-30 16:00:00";13.9;324;59
"""
# continue as in the JSON case...

If your CSV data is in a file, you can read the file content into a string as follows (Python):

with open('file.csv', 'r') as f:
    data = f.read()

or (PHP):

$data = file_get_contents('file.csv');