Основное окно
Разметка основного окна ничем не отличается от разметки любой другой веб-страницы. Вдобавок нам предоставляют несколько исключительно гаджетовских тегов. Для задания фона гаджета, используется тег
g:background
. Любое содержимое, размещенное в данном элементе будет фоновым для всего основного окна.
Я не стал делать задний фон гаджету, с помощью параметра opacity=«0» фон стал абсолютно прозрачным.
Тело страницы довольно простое верхний div служит для отображения статуса гаджета, позволяет увидеть, сколько минут осталось до обновления данных, а также поддерживает ручное обновление. Нижний div будет содержать в себе список серверов.
Gadget.xml
Мы укажем в манифесте минимально нужную информацию.
The best smart gadgets for your home
The range of smart home gadgets available is constantly growing, with just about every household or entertainment appliance now available as a connected, online device. Some, like the home hubs and connected thermostats, have been around for a while and have gone through several generations of refinements and added functionality. Others are new to the online world, and to be honest, you may never have even realized you needed a connected version until now!
Here’s my pick of the best, the most interesting or the most innovative offerings on the market, which are either available now or coming soon!
Orro intelligent light switch
There are a few different wifi-enabled lighting systems available now, but Orro’s is the first that aims to use self-learning technology to understand how you like to light your home and anticipate your mood lighting needs in advance.
As well as sensing when people enter or leave a room, it comes to understand your lighting preferences and how they change according to the time of day, as well as the natural light entering the room. It can also connect to smart hubs such as Amazon’s Alexa, and act as an extension to their voice recognition capabilities.
Netatmo indoor security camera
Again, there are dozens of wifi-enabled security camera systems marketed to the domestic user these days, but Netamo’s device takes things a step further by incorporating actual artificial intelligence, in the form of facial recognition abilities.
This means it’s able to distinguish between people who should and shouldn’t be in your property and alert you, wherever in the world you happen to be. Thanks to it also having smart listening capabilities, it can even recognize when alarms like smoke or carbon monoxide detectors have activated. It can also be set to only record when unidentified faces are present – meaning it will respect the privacy of people who are authorized to be in the house.
Nest Smart Thermostat
The Nest thermostat has been around for a while now and has proven its value in millions of homes, becoming one of the most popular smart home gadgets available. In fact, Nest (a subsidiary of Google) claim their thermostat has saved 8 billion kW of energy since it was released back in 2021.
It works by understanding patterns in how a home is heated, and learning to adjust temperatures to match its owner’s lifestyle automatically. Rather than program it as you would a traditional thermostat, you simply adjust it to your preferred temperature at different times, and Nest learns your schedule. It also detects when you leave or arrive at home, by detecting signals from your phone, and uses this information to avoid wasting energy.
August Smart Lock Pro
This is a smart lock that attaches to a front door, automatically granting access when you approach and securing your home when you leave – but that’s just the start of what it can do.
Guest access can be assigned for friends, visitors, or cleaners, meaning there’s no need to get copies of keys made if you need to let others access your home while you’re not around. This could be particularly useful if you’re one of the growing number of people who make some extra money by renting out spare rooms through services like Airbnb!
You can also check on the status of your door at any time, wherever you are, to find out whether anyone’s been coming and going from your home while you’re away.
Signature Kitchen Suite
This one is perhaps not in everyone’s price range – The Signature Kitchen Suite (which is backed by LG) is an AI-equipped wine fridge for the serious wine connoisseur with money to spare. It combines state-of-the-art refrigeration and anti-vibration technology, designed to keep the most exquisite wines in perfect condition, with the True Sommelier app powered by Wine Ring. This app learns to understand its users’ wine preferences by using data gathered from a worldwide network of wine experts and can suggest the perfect accompaniment for any meal.
Ikea Smart Blinds
The Swedish superstore’s take on the smart blind is not yet available – originally due to be released at the beginning of the year, their launch has now been delayed until later in the summer. However, with its voice-activated, smartphone-connected blinds, Ikea aims to do what it does best by making expensive home décor available in an affordable and stylish mass-market form.
Available in standard and blackout editions, in three different sizes, the blinds are compatible with Siri, Alexa and Google home, as well as Ikea’s own Tradfri smart home system.
Dyson 360 Eye
Robotic vacuum cleaners have also been around for a while now – and operate with varying degrees of success. Dyson clearly believe they have cracked it, though, with their latest attempt. As the name suggests, the 360 Eye relies on 360-degree camera coverage to navigate across your floor – rather than taking the approach used by most of its competitors of merely traveling in a straight line until it hits a wall, then setting off in a different direction.
This means the robot can cover more floor space more efficiently, getting more of the job done before it has to return to its docking station to recharge. You can also use the supplied app to monitor how proficient it has been at covering the whole floor area. Additionally, tank-style caterpillar tracks, rather than the more usual wheels, mean it is better equipped to handle varying floor levels. Of course, it can’t climb up steps, but it should manage to transition between wood flooring and rugs, without thinking it has hit an insurmountable obstacle.
The Pod smart bed
The latest development from smart sleep specialists 8 Sleep, the Pod learns the temperature you like to sleep at and regulates itself to give you the best chance of a good night’s rest. It can also wake you up by gradually raising the temperature of the bed, eliminating the need for the rude awakening provided by alarms.
For a $5 monthly subscription (the first year is included in the price of the Pod), a connected app will also analyze data collected while you sleep by sensors in the mattress, and everything is also controllable by voice thanks to Alexa compatibility.
iKuddle smart cat litter tray
Having just smashed through its target on Kickstarter, the iKuddle litter tray isn’t available just yet, but there’s clearly a lot of people very interested in the idea of a self-cleaning, sensor-activated litter tray.
The iKuddle detects when your cat enters the tray, scoops up the soiled litter, automatically seals it in an airtight bag, and dispenses a burst of deodorant to get rid of unwelcome odors.
Another selling point for cat lovers is that it will also monitor your beloved pet’s health by recording and tracking the regularity of toilet trips, alerting you to any changes in lavatorial habits which could indicate illness or the need for a check-up.
Сестра, скальпель
Гаджет – это обыкновенный zip-файл, который внутри себя хранит нужную информацию для развертывания. Сам гаджет – это набор HTML, CSS, JavaScript файлов, изображений и т.д.
Гаджет состоит из нескольких файлов с условными названиями:
Для управления поведением, видом гаджета,, хранения данных используется специальный объект System.Gadget.
Темная сторона, люк
Самый главный файл – JavaScript. Сразу оговорюсь, alert и confirm в гаджетах не работают. Для отладки гаджета, можно воспользоваться Visual Studio, но для этого нужно выполнить два хитрых действия. Прежде всего, включить отладчик JavaScript в Internet Explorer
Добавить в нужном месте кода гаджета строку:
debugger;
и перезапустить гаджет.
Мы объявляем две глобальных переменных, которые отвечают за время в минутах для обновления данных в гаджете, для меня оптимально 30 минут, а также счетчик отсчета оставшихся минут до обновления
var updateInterval = 30;
var updateMinutes = updateInterval;
Функция init содержит действия для инициализации гаджета, мне в данном случае было нужно установить прозрачность гаджета на 40%, чтобы он не перекрывал полностью кусочек рабочего стола.
function init() {
System.Gadget.Settings.write("PrivateSetting_GadgetOpacity", 40);
}
Функция запуска самого мониторинга, которая обновляет список серверов с их статусом, устанавливает интервал обновления данных, таймера в главном окне и так же добавляет обработчик события для ручного обновления статуса серверов.
function startMonitoring() {
init();
updateList();
setInterval(updateList, updateInterval * 1000 * 60);
setInterval(updateTimer, 1000 * 60);
statusLink.onclick = function() {
updateList();
}
}
Добавление обработчика на нажатие происходит в данном случае двумя способами:
element.onclick = function(){}
$(element).get(0).onclick = function(){}
Продвинутые способы в гаджетах не работают:
element.attachEvent('onclick', function(){})
$(element).bind('click', function(){})
Для обновления самого таймера маленькая функция updateTimer, которая каждую минуту рассчитывает сколько времени осталось до обновления.
function updateTimer() {
updateMinutes = updateMinutes == 0 ? updateInterval : updateMinutes - 1;
$('#statusLink').html('Update in ' updateMinutes ' m.');
}
И наконец, обновление списка серверов, для возвращенных данных я использую JSON, вид ответа примерно такой:
[{«ip»:«***.45.**.60»,«lastHitTime»:«2009-09-06 00:07:24»,«runningTasks»:«1»}]
https://www.youtube.com/channel/UCNDy4lRk4FIfufXtP5PaNQQ
Для получения самих данных – getJSON. Вы можете использовать и AJAX, он прекрасно работает в гаджетах. Прежде всего, используя getJSON мы можем отлаживать код в браузере, не добавляя его в гаджет, AJAX нам такое сделать не позволит. В зависимости от загрузки сервера, я закрашиваю ячейку разным фоном.