How to integrate a new connector?

Xibo ships by default National Weather Service Connector, in Europe we have a similar service that provides meteo alams also based on atom dataformat https://feeds.meteoalarm.org/
It provide data by polling but also by publish/subscribe
I would like to integrate this feeds in xibo.
Which is the proper procedure from a developer point of view to integrate a new connector ?

I answer by myself:
<?php
/*
* Open-Meteo connector for Weather widget (dataSource 'forecastio').
* Install in custom/OpenMeteoConnector.php (namespace Xibo\Custom).
*/

namespace Xibo\Custom;

use Carbon\Carbon;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Str;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Xibo\Connector\ConnectorInterface;
use Xibo\Connector\ConnectorTrait;
use Xibo\Event\WidgetDataRequestEvent;
use Xibo\Factory\DisplayFactory;
use Xibo\Helper\GeoHelper;
use Xibo\Support\Exception\GeneralException;
use Xibo\Support\Sanitizer\SanitizerInterface;
use Xibo\Widget\DataType\Forecast;
use Xibo\Widget\Provider\DataProviderInterface;

class OpenMeteoConnector implements ConnectorInterface
{
use ConnectorTrait;

private const API_URL = '``https://api.open-meteo.com/v1/forecast``';
private const DEFAULT_SOURCE = 'ref1_address';

private const LOCATION_SOURCES = [
'ref1_address' => 'Reference 1, otherwise Address',
'ref1' => 'Reference 1',
'ref2' => 'Reference 2',
'ref3' => 'Reference 3',
'ref4' => 'Reference 4',
'ref5' => 'Reference 5',
'address' => 'Address',
'display' => 'Display name',
'none' => 'None (empty)',
];

private const H_MORNING = 6;
private const H_NOON = 12;
private const H_EVENING = 18;
private const H_NIGHT = 22;

private DisplayFactory $displayFactory;

public function setFactories(ContainerInterface $container): ConnectorInterface
{
$this->displayFactory = $container->get('displayFactory');
return $this;
}

public function registerWithDispatcher(EventDispatcherInterface $dispatcher): ConnectorInterface
{
$dispatcher->addListener(WidgetDataRequestEvent::$NAME, [$this, 'onDataRequest']);
return $this;
}

public function getSourceName(): string
{
return 'openmeteo';
}

public function getTitle(): string
{
return 'Open-Meteo';
}

public function getDescription(): string
{
return 'Get Weather data from the Open-Meteo API';
}

public function getThumbnail(): string
{
return '';
}

public function getSettingsFields(): array
{
$options = [];
foreach (self::LOCATION_SOURCES as $value => $label) {
$options[] = ['value' => $value, 'label' => __($label)];
}

return [
[
'name' => 'locationSource',
'type' => 'select',
'label' => __('Location name source'),
'helpText' => __(
'Display field used as the location name. Only applies when the widget uses the display location.'
. ' Address is cut at the first " - ".'
),
'default' => self::DEFAULT_SOURCE,
'options' => $options,
],
[
'name' => 'cachePeriod',
'type' => 'number',
'label' => __('Cache Period'),
'helpText' => __('Seconds to cache weather results.'),
'default' => 3600,
],
];
}

public function processSettingsForm(SanitizerInterface $params, array $settings): array
{
$source = (string)$params->getString('locationSource');
$settings['locationSource'] = array_key_exists($source, self::LOCATION_SOURCES)
? $source
: self::DEFAULT_SOURCE;

$period = $params->getInt('cachePeriod');
$settings['cachePeriod'] = $period ? max(60, $period) : 3600;

return $settings;
}

public function onDataRequest(WidgetDataRequestEvent $event)
{
$provider = $event->getDataProvider();
if ($provider->getDataSource() !== 'forecastio') {
return;
}

$event->stopPropagation();

try {
$this->getWeatherData($provider);
$provider->setCacheTtl((int)$this->getSetting('cachePeriod', 3600));
$provider->setIsHandled();
} catch (\Throwable $e) {
$this->getLogger()->error('OpenMeteo: ' . $e->getMessage());
$provider->addError(__('Unable to get weather results.'));
}
}

private function getWeatherData(DataProviderInterface $provider): void
{
if ($provider->getProperty('useDisplayLocation') == 0) {
$lat = $provider->getProperty('latitude', $provider->getDisplayLatitude());
$lon = $provider->getProperty('longitude', $provider->getDisplayLongitude());
} else {
$lat = $provider->getDisplayLatitude();
$lon = $provider->getDisplayLongitude();
}

$lat = GeoHelper::roundCoordinate($lat);
$lon = GeoHelper::roundCoordinate($lon);
if ($lat === null || $lon === null) {
throw new GeneralException('No coordinates available');
}

$lang = $provider->getProperty('lang', 'en');
$data = $this->queryApi($lat, $lon);

$tz = $data['timezone'] ?? 'UTC';
$unit = $this->resolveUnit($provider->getProperty('units', 'auto'), $tz);

$dayOnly = $provider->getProperty('dayConditionsOnly', 0) == 1;
$current = $this->buildCurrent($data, $unit, $lang, $dayOnly);

// Oggi serve per max/min del "current"; i giorni successivi sono i forecast
$days = $data['daily']['time'] ?? [];
$today = null;
$forecasts = [];
foreach ($days as $i => $dt) {
$f = $this->buildDay($data, $i, $unit, $lang);
if ($i === 0) {
$today = $f;
} else {
$forecasts[] = $f;
}
}

if ($today !== null) {
foreach ([
'temperatureHigh', 'temperatureMaxRound', 'temperatureLow', 'temperatureMinRound',
'temperatureMorning', 'temperatureMorningRound', 'temperatureNight', 'temperatureNightRound',
'temperatureEvening', 'temperatureEveningRound', 'temperatureMean', 'temperatureMeanRound',
] as $field) {
$current->$field = $today->$field;
}
}

$location = $this->getDisplayLabel($provider);
$current->location = $location;
$provider->addItem($current);
foreach ($forecasts as $f) {
$f->location = $location;
$provider->addItem($f);
}
$provider->addOrUpdateMeta('Attribution', 'Weather data by ``Open-Meteo.com``');
}

/** Location name see source in settings ( */
private function getDisplayLabel(DataProviderInterface $provider): string
{
$source = $this->getSetting('locationSource', self::DEFAULT_SOURCE);
$displayId = $provider->getDisplayId();
if ($source === 'none' || $provider->getProperty('useDisplayLocation') == 0 || $displayId <= 0) {
$this->getLogger()->debug('OpenMeteo: no location label, source ' . $source . ', displayId ' . $displayId);
return '';
}

try {
$display = $this->displayFactory->getById($displayId);
} catch (\Exception $e) {
$this->getLogger()->error('OpenMeteo: display ' . $displayId . ' not found');
return '';
}

$address = trim(explode(' - ', (string)$display->address, 2)[0]);

$label = match ($source) {
'ref1_address' => trim((string)$display->ref1) ?: $address,
'ref1', 'ref2', 'ref3', 'ref4', 'ref5' => trim((string)$display->$source),
'address' => $address,
'display' => trim((string)$display->display),
default => '',
};
$this->getLogger()->debug('OpenMeteo: display ' . $displayId . ' location (' . $source . ') = \'' . $label . '\'');

return $label;
}

private function queryApi(float $lat, float $lon): array
{
$cache = $this->pool->getItem('/weather/openmeteo/' . md5($lat . '_' . $lon));
$data = $cache->get();

if ($cache->isHit()) {
return $data;
}

$cache->lock();
$query = http_build_query([
'latitude' => $lat,
'longitude' => $lon,
'current' => 'temperature_2m,apparent_temperature,relative_humidity_2m,is_day,weather_code,'
. 'cloud_cover,pressure_msl,wind_speed_10m,wind_direction_10m',
'hourly' => 'temperature_2m,apparent_temperature,relative_humidity_2m,pressure_msl,cloud_cover,'
. 'visibility,dew_point_2m,wind_speed_10m,wind_direction_10m',
'daily' => 'weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset,uv_index_max',
'wind_speed_unit' => 'ms',
'timeformat' => 'unixtime',
'timezone' => 'auto',
'forecast_days' => 8,
]);

try {
$response = $this->getClient()->get(self::API_URL . '?' . $query);
if ($response->getStatusCode() != 200) {
throw new GeneralException('Non-200 response from Open-Meteo');
}
$data = json_decode($response->getBody(), true);
if (!is_array($data) || empty($data['daily'])) {
throw new GeneralException('Unexpected response from Open-Meteo');
}
$cache->set($data);
$cache->expiresAt(Carbon::now()->addSeconds((int)$this->getSetting('cachePeriod', 3600)));
$this->pool->saveDeferred($cache);
} catch (RequestException $e) {
throw new GeneralException('Unable to reach Open-Meteo: ' . $e->getMessage());
}

return $data;
}

private function newForecast(array $unit): Forecast
{
$f = new Forecast();
$f->temperatureUnit = $unit['tempUnit'];
$f->windSpeedUnit = $unit['windUnit'];
$f->visibilityDistanceUnit = $unit['visibilityUnit'];
$f->location = '';
$f->ozone = '--';
return $f;
}

private function buildCurrent(array $data, array $unit, string $lang, bool $dayOnly): Forecast
{
$c = $data['current'];
$h = $data['hourly'];
$idx = max(0, (int)floor(($c['time'] - $h['time'][0]) / 3600));

$f = $this->newForecast($unit);
$f->time = $c['time'];
$f->sunRise = $data['daily']['sunrise'][0] ?? null;
$f->sunSet = $data['daily']['sunset'][0] ?? null;
$this->setCommon(
$f,
$c['weather_code'],
$dayOnly || $c['is_day'] == 1,
$lang,
$c['temperature_2m'],
$c['apparent_temperature'],
$c['relative_humidity_2m'],
$c['pressure_msl'],
$c['wind_speed_10m'],
$c['wind_direction_10m'],
$c['cloud_cover'],
$h['visibility'][$idx] ?? null,
$h['dew_point_2m'][$idx] ?? null,
$data['daily']['uv_index_max'][0] ?? null,
$unit
);
$f->temperatureHigh = $f->temperatureLow = $f->temperatureNight = $f->temperature;
$f->temperatureEvening = $f->temperatureMorning = $f->temperature;
$f->temperatureMean = $f->temperature;
$this->round($f);
return $f;
}

private function buildDay(array $data, int $i, array $unit, string $lang): Forecast
{
$d = $data['daily'];
$h = $data['hourly'];
$at = fn(string $key, int $hour) => $h[$key][$i * 24 + $hour] ?? null;
$conv = fn($v) => $v === null ? null : $this->temp((float)$v, $unit);

$f = $this->newForecast($unit);
$f->time = $d['time'][$i];
$f->sunRise = $d['sunrise'][$i] ?? null;
$f->sunSet = $d['sunset'][$i] ?? null;
$this->setCommon(
$f,
$d['weather_code'][$i],
true,
$lang,
$at('temperature_2m', self::H_NOON),
$at('apparent_temperature', self::H_NOON),
$at('relative_humidity_2m', self::H_NOON),
$at('pressure_msl', self::H_NOON),
$at('wind_speed_10m', self::H_NOON),
$at('wind_direction_10m', self::H_NOON),
$at('cloud_cover', self::H_NOON),
$at('visibility', self::H_NOON),
$at('dew_point_2m', self::H_NOON),
$d['uv_index_max'][$i] ?? null,
$unit
);
$f->temperatureHigh = $conv($d['temperature_2m_max'][$i] ?? null);
$f->temperatureLow = $conv($d['temperature_2m_min'][$i] ?? null);
$f->temperatureMorning = $conv($at('temperature_2m', self::H_MORNING));
$f->temperatureEvening = $conv($at('temperature_2m', self::H_EVENING));
$f->temperatureNight = $conv($at('temperature_2m', self::H_NIGHT));
$f->temperatureMean = ($f->temperatureHigh !== null && $f->temperatureLow !== null)
? ($f->temperatureHigh + $f->temperatureLow) / 2
: $f->temperature;
$this->round($f);
return $f;
}

/** Valori in unità Open-Meteo: °C, m/s, m, hPa */
private function setCommon(
Forecast $f,
$code,
bool $isDay,
string $lang,
$temp,
$feels,
$humidity,
$pressure,
$wind,
$bearing,
$clouds,
$visibility,
$dew,
$uv,
array $unit
): void {
$f->temperature = $temp === null ? null : $this->temp((float)$temp, $unit);
$f->apparentTemperature = $feels === null ? null : $this->temp((float)$feels, $unit);
$f->dewPoint = $dew === null ? '--' : $this->temp((float)$dew, $unit);

$f->humidityPercent = $humidity;
$f->humidity = $humidity === null ? null : $humidity / 100;
$f->pressure = $pressure;
$f->cloudCover = $clouds;
$f->uvIndex = $uv ?? '--';

$f->windSpeed = $wind === null ? null : match ($unit['windUnit']) {
'MPH' => round($wind * 2.237, 2),
'KPH' => round($wind * 3.6, 2),
default => round($wind, 2),
};
$f->windBearing = $bearing;
$f->windDirection = $this->cardinal($bearing);

if ($visibility === null) {
$f->visibility = '--';
} elseif ($unit['visibilityUnit'] === 'mi') {
$f->visibility = $visibility / 1609;
} else {
$f->visibility = $visibility / 1000;
}

[$wicon, $background, $summary] = $this->describe((int)$code, $isDay, $lang);
$f->summary = $summary;
$f->icon = $background;
$f->wicon = $wicon;
}

private function round(Forecast $f): void
{
$r = fn($v) => is_numeric($v) ? round((float)$v, 0) : null;

$f->temperatureRound = $r($f->temperature);
$f->apparentTemperatureRound = $r($f->apparentTemperature);
$f->temperatureNightRound = $r($f->temperatureNight);
$f->temperatureMorningRound = $r($f->temperatureMorning);
$f->temperatureEveningRound = $r($f->temperatureEvening);
$f->temperatureMaxRound = $r($f->temperatureHigh);
$f->temperatureMinRound = $r($f->temperatureLow);
$f->temperatureMeanRound = $r($f->temperatureMean);
}

private function temp(float $celsius, array $unit): float
{
return $unit['tempUnit'] === 'F' ? $celsius * 9 / 5 + 32 : $celsius;
}

private function cardinal($bearing): string
{
if (!is_numeric($bearing)) {
return '--';
}
$dirs = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
$deg = fmod(fmod((float)$bearing, 360) + 360, 360);
return $dirs[(int)round($deg / 45) % 8];
}

private function resolveUnit(string $code, string $timezone): array
{
$units = [
'ca' => ['tempUnit' => 'C', 'windUnit' => 'KPH', 'visibilityUnit' => 'km'],
'si' => ['tempUnit' => 'C', 'windUnit' => 'MPS', 'visibilityUnit' => 'km'],
'uk2' => ['tempUnit' => 'C', 'windUnit' => 'MPH', 'visibilityUnit' => 'mi'],
'us' => ['tempUnit' => 'F', 'windUnit' => 'MPH', 'visibilityUnit' => 'mi'],
];
if (isset($units[$code])) {
return $units[$code];
}
if (Str::startsWith($timezone, 'America')) {
return $units['us'];
}
return $timezone === 'Europe/London' ? $units['uk2'] : $units['si'];
}

/** WMO weather code -> [codice icona stile OWM, descrizione] */
/**
* Codice WMO -> [classe icona (Weather Icons), sfondo, descrizione].
* Per ogni codice: icona giorno, icona notte, sfondo giorno, sfondo notte, testo it, testo en.
*/
private function describe(int $code, bool $isDay, string $lang): array
{
$it = str_starts_with($lang, 'it');
$map = [
0 => ['wi-day-sunny', 'wi-night-clear', 'clear-day', 'clear-night', 'Sereno', 'Clear sky'],
1 => ['wi-day-sunny-overcast', 'wi-night-alt-partly-cloudy', 'clear-day', 'clear-night', 'Prevalentemente sereno', 'Mainly clear'],
2 => ['wi-day-cloudy', 'wi-night-alt-cloudy', 'partly-cloudy-day', 'partly-cloudy-night', 'Parzialmente nuvoloso', 'Partly cloudy'],
3 => ['wi-cloudy', 'wi-cloudy', 'cloudy', 'cloudy', 'Coperto', 'Overcast'],
45 => ['wi-day-fog', 'wi-night-fog', 'fog', 'fog', 'Nebbia', 'Fog'],
48 => ['wi-day-fog', 'wi-night-fog', 'fog', 'fog', 'Nebbia con brina', 'Rime fog'],
51 => ['wi-day-sprinkle', 'wi-night-sprinkle', 'rain', 'rain', 'Pioggerella leggera', 'Light drizzle'],
53 => ['wi-day-sprinkle', 'wi-night-sprinkle', 'rain', 'rain', 'Pioggerella', 'Drizzle'],
55 => ['wi-sprinkle', 'wi-sprinkle', 'rain', 'rain', 'Pioggerella intensa', 'Dense drizzle'],
56 => ['wi-day-sleet', 'wi-night-sleet', 'rain', 'rain', 'Pioggerella gelata', 'Freezing drizzle'],
57 => ['wi-day-sleet', 'wi-night-sleet', 'rain', 'rain', 'Pioggerella gelata intensa', 'Dense freezing drizzle'],
61 => ['wi-day-rain', 'wi-night-rain', 'rain', 'rain', 'Pioggia debole', 'Slight rain'],
63 => ['wi-rain', 'wi-rain', 'rain', 'rain', 'Pioggia', 'Rain'],
65 => ['wi-rain', 'wi-rain', 'rain', 'rain', 'Pioggia intensa', 'Heavy rain'],
66 => ['wi-day-sleet', 'wi-night-sleet', 'rain', 'rain', 'Pioggia gelata', 'Freezing rain'],
67 => ['wi-day-sleet', 'wi-night-sleet', 'rain', 'rain', 'Pioggia gelata intensa', 'Heavy freezing rain'],
71 => ['wi-day-snow', 'wi-night-snow', 'snow', 'snow', 'Neve debole', 'Slight snow'],
73 => ['wi-snow', 'wi-snow', 'snow', 'snow', 'Neve', 'Snow'],
75 => ['wi-snow', 'wi-snow', 'snow', 'snow', 'Neve intensa', 'Heavy snow'],
77 => ['wi-snow', 'wi-snow', 'snow', 'snow', 'Granelli di neve', 'Snow grains'],
80 => ['wi-day-showers', 'wi-night-showers', 'rain', 'rain', 'Rovesci deboli', 'Slight showers'],
81 => ['wi-day-showers', 'wi-night-showers', 'rain', 'rain', 'Rovesci', 'Showers'],
82 => ['wi-day-storm-showers', 'wi-night-storm-showers', 'rain', 'rain', 'Rovesci violenti', 'Violent showers'],
85 => ['wi-day-snow', 'wi-night-snow', 'snow', 'snow', 'Rovesci di neve', 'Snow showers'],
86 => ['wi-day-snow', 'wi-night-snow', 'snow', 'snow', 'Rovesci di neve intensi', 'Heavy snow showers'],
95 => ['wi-day-thunderstorm', 'wi-night-thunderstorm', 'wind', 'wind', 'Temporale', 'Thunderstorm'],
96 => ['wi-day-sleet-storm', 'wi-night-sleet-storm', 'wind', 'wind', 'Temporale con grandine', 'Thunderstorm with hail'],
99 => ['wi-day-sleet-storm', 'wi-night-sleet-storm', 'wind', 'wind', 'Temporale con grandine forte', 'Thunderstorm with heavy hail'],
];
[$wiDay, $wiNight, $bgDay, $bgNight, $itText, $enText] = $map[$code]
?? ['wi-cloudy', 'wi-cloudy', 'cloudy', 'cloudy', 'Nuvoloso', 'Cloudy'];

return [$isDay ? $wiDay : $wiNight, $isDay ? $bgDay : $bgNight, $it ? $itText : $enText];
}
}

enable the module using SQL…

INSERT INTO connectors (className, isEnabled, isVisible) VALUES ('\\Xibo\\Custom\\OpenMeteoConnector', 0, 1);