]> git.basschouten.com Git - openhab-addons.git/blob
36ba69e204a1b1dc193492251168885dc4016b90
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.systeminfo.internal.handler;
14
15 import static org.openhab.binding.systeminfo.internal.SysteminfoBindingConstants.*;
16
17 import java.math.BigDecimal;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.HashSet;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
27 import java.util.stream.Collectors;
28
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.openhab.binding.systeminfo.internal.SysteminfoThingTypeProvider;
32 import org.openhab.binding.systeminfo.internal.model.DeviceNotFoundException;
33 import org.openhab.binding.systeminfo.internal.model.SysteminfoInterface;
34 import org.openhab.core.cache.ExpiringCache;
35 import org.openhab.core.cache.ExpiringCacheMap;
36 import org.openhab.core.config.core.Configuration;
37 import org.openhab.core.library.types.DecimalType;
38 import org.openhab.core.library.types.PercentType;
39 import org.openhab.core.library.types.QuantityType;
40 import org.openhab.core.library.unit.Units;
41 import org.openhab.core.thing.Channel;
42 import org.openhab.core.thing.ChannelUID;
43 import org.openhab.core.thing.Thing;
44 import org.openhab.core.thing.ThingStatus;
45 import org.openhab.core.thing.ThingStatusDetail;
46 import org.openhab.core.thing.ThingTypeUID;
47 import org.openhab.core.thing.ThingUID;
48 import org.openhab.core.thing.binding.BaseThingHandler;
49 import org.openhab.core.thing.binding.builder.ThingBuilder;
50 import org.openhab.core.thing.type.ChannelGroupDefinition;
51 import org.openhab.core.types.Command;
52 import org.openhab.core.types.RefreshType;
53 import org.openhab.core.types.State;
54 import org.openhab.core.types.UnDefType;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 /**
59  * The {@link SysteminfoHandler} is responsible for providing real time information about the system
60  * (CPU, Memory, Storage, Display and others).
61  *
62  * @author Svilen Valkanov - Initial contribution
63  * @author Lyubomir Papzov - Separate the creation of the systeminfo object and its initialization
64  * @author Wouter Born - Add null annotations
65  * @author Mark Herwege - Add dynamic creation of extra channels
66  */
67 @NonNullByDefault
68 public class SysteminfoHandler extends BaseThingHandler {
69     /**
70      * Refresh interval for {@link #highPriorityChannels} in seconds.
71      */
72     private @NonNullByDefault({}) BigDecimal refreshIntervalHighPriority;
73
74     /**
75      * Refresh interval for {@link #mediumPriorityChannels} in seconds.
76      */
77     private @NonNullByDefault({}) BigDecimal refreshIntervalMediumPriority;
78
79     /**
80      * Channels with priority configuration parameter set to High. They usually need frequent update of the state like
81      * CPU load, or information about the free and used memory.
82      * They are updated periodically at {@link #refreshIntervalHighPriority}.
83      */
84     private final Set<ChannelUID> highPriorityChannels = new HashSet<>();
85
86     /**
87      * Channels with priority configuration parameter set to Medium. These channels usually need update of the
88      * state not so oft like battery capacity, storage used and etc.
89      * They are updated periodically at {@link #refreshIntervalMediumPriority}.
90      */
91     private final Set<ChannelUID> mediumPriorityChannels = new HashSet<>();
92
93     /**
94      * Channels with priority configuration parameter set to Low. They represent static information or information
95      * that is updated rare- e.g. CPU name, storage name and etc.
96      * They are updated only at {@link #initialize()}.
97      */
98     private final Set<ChannelUID> lowPriorityChannels = new HashSet<>();
99
100     /**
101      * Wait time for the creation of Item-Channel links in seconds. This delay is needed, because the Item-Channel
102      * links have to be created before the thing state is updated, otherwise item state will not be updated.
103      */
104     public static final int WAIT_TIME_CHANNEL_ITEM_LINK_INIT = 1;
105
106     /**
107      * String used to extend thingUID and channelGroupTypeUID for thing definition with added dynamic channels and
108      * extended channels. It is set in the constructor and unique to the thing.
109      */
110     public final String idExtString;
111
112     public final SysteminfoThingTypeProvider thingTypeProvider;
113
114     private SysteminfoInterface systeminfo;
115
116     private @Nullable ScheduledFuture<?> highPriorityTasks;
117     private @Nullable ScheduledFuture<?> mediumPriorityTasks;
118
119     /**
120      * Caches for cpu process load and process load for a given pid. Using this cache limits the process load refresh
121      * interval to the minimum interval. Too frequent refreshes leads to inaccurate results. This could happen when the
122      * same process is tracked as current process and as a channel with pid parameter, or when the task interval is set
123      * too low.
124      */
125     private static final int MIN_PROCESS_LOAD_REFRESH_INTERVAL_MS = 2000;
126     private ExpiringCache<PercentType> cpuLoadCache = new ExpiringCache<>(MIN_PROCESS_LOAD_REFRESH_INTERVAL_MS,
127             () -> getSystemCpuLoad());
128     private ExpiringCacheMap<Integer, @Nullable DecimalType> processLoadCache = new ExpiringCacheMap<>(
129             MIN_PROCESS_LOAD_REFRESH_INTERVAL_MS);
130
131     private final Logger logger = LoggerFactory.getLogger(SysteminfoHandler.class);
132
133     public SysteminfoHandler(Thing thing, SysteminfoThingTypeProvider thingTypeProvider,
134             SysteminfoInterface systeminfo) {
135         super(thing);
136         this.thingTypeProvider = thingTypeProvider;
137         this.systeminfo = systeminfo;
138
139         idExtString = "-" + thing.getUID().getId();
140     }
141
142     @Override
143     public void initialize() {
144         logger.trace("Initializing thing {} with thing type {}", thing.getUID().getId(),
145                 thing.getThingTypeUID().getId());
146         restoreChannelsConfig(); // After a thing type change, previous channel configs will have been stored, and will
147                                  // be restored here.
148         if (instantiateSysteminfoLibrary() && isConfigurationValid() && updateProperties()) {
149             if (!addDynamicChannels()) { // If there are new channel groups, the thing will get recreated with a new
150                                          // thing type and this handler will be disposed. Therefore do not do anything
151                                          // further here.
152                 groupChannelsByPriority();
153                 scheduleUpdates();
154                 updateStatus(ThingStatus.ONLINE);
155             }
156         } else {
157             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR,
158                     "@text/offline.cannot-initialize");
159         }
160     }
161
162     @Override
163     public void handleRemoval() {
164         thingTypeProvider.removeThingType(thing.getThingTypeUID());
165         super.handleRemoval();
166     }
167
168     private boolean instantiateSysteminfoLibrary() {
169         try {
170             systeminfo.initializeSysteminfo();
171             logger.debug("Systeminfo implementation is instantiated!");
172             return true;
173         } catch (Exception e) {
174             logger.warn("Cannot instantiate Systeminfo object!", e);
175             return false;
176         }
177     }
178
179     private boolean isConfigurationValid() {
180         logger.debug("Start reading Thing configuration.");
181         try {
182             refreshIntervalMediumPriority = (BigDecimal) this.thing.getConfiguration()
183                     .get(MEDIUM_PRIORITY_REFRESH_TIME);
184             refreshIntervalHighPriority = (BigDecimal) this.thing.getConfiguration().get(HIGH_PRIORITY_REFRESH_TIME);
185
186             if (refreshIntervalHighPriority.intValue() <= 0 || refreshIntervalMediumPriority.intValue() <= 0) {
187                 throw new IllegalArgumentException("Refresh time must be positive number!");
188             }
189             logger.debug("Refresh time for medium priority channels set to {} s", refreshIntervalMediumPriority);
190             logger.debug("Refresh time for high priority channels set to {} s", refreshIntervalHighPriority);
191             return true;
192         } catch (IllegalArgumentException e) {
193             logger.warn("Refresh time value is invalid! Please change the thing configuration!");
194             return false;
195         } catch (ClassCastException e) {
196             logger.debug("Channel configuration cannot be read!");
197             return false;
198         }
199     }
200
201     private boolean updateProperties() {
202         Map<String, String> properties = editProperties();
203         try {
204             properties.put(PROPERTY_CPU_LOGICAL_CORES, systeminfo.getCpuLogicalCores().toString());
205             properties.put(PROPERTY_CPU_PHYSICAL_CORES, systeminfo.getCpuPhysicalCores().toString());
206             properties.put(PROPERTY_OS_FAMILY, systeminfo.getOsFamily().toString());
207             properties.put(PROPERTY_OS_MANUFACTURER, systeminfo.getOsManufacturer().toString());
208             properties.put(PROPERTY_OS_VERSION, systeminfo.getOsVersion().toString());
209             updateProperties(properties);
210             logger.debug("Properties updated!");
211             return true;
212         } catch (Exception e) {
213             logger.debug("Cannot get system properties! Please try to restart the binding.", e);
214             return false;
215         }
216     }
217
218     /**
219      * Retrieve info on available storages, drives, displays, batteries, network interfaces and fans in the system. If
220      * there is more than 1, create additional channel groups and channels representing each of the entities with an
221      * index added to the channel groups and channels. The base channel groups and channels will remain without index
222      * and are equal to the channel groups and channels with index 0. If there is only one entity in a group, do not add
223      * a channels group and channels with index 0.
224      * <p>
225      * If channel groups are added, the thing type will change to systeminfo:computer-Ext, with Ext equal to the thing
226      * id. A new handler will be created and initialization restarted. Therefore further initialization of the current
227      * handler can be aborted if the method returns true.
228      *
229      * @return true if channel groups where added
230      */
231     private boolean addDynamicChannels() {
232         ThingUID thingUID = thing.getUID();
233
234         List<ChannelGroupDefinition> newChannelGroups = new ArrayList<>();
235         newChannelGroups.addAll(createChannelGroups(thingUID, CHANNEL_GROUP_STORAGE, CHANNEL_GROUP_TYPE_STORAGE,
236                 systeminfo.getFileOSStoreCount()));
237         newChannelGroups.addAll(createChannelGroups(thingUID, CHANNEL_GROUP_DRIVE, CHANNEL_GROUP_TYPE_DRIVE,
238                 systeminfo.getDriveCount()));
239         newChannelGroups.addAll(createChannelGroups(thingUID, CHANNEL_GROUP_DISPLAY, CHANNEL_GROUP_TYPE_DISPLAY,
240                 systeminfo.getDisplayCount()));
241         newChannelGroups.addAll(createChannelGroups(thingUID, CHANNEL_GROUP_BATTERY, CHANNEL_GROUP_TYPE_BATTERY,
242                 systeminfo.getPowerSourceCount()));
243         newChannelGroups.addAll(createChannelGroups(thingUID, CHANNEL_GROUP_NETWORK, CHANNEL_GROUP_TYPE_NETWORK,
244                 systeminfo.getNetworkIFCount()));
245         if (!newChannelGroups.isEmpty()) {
246             logger.debug("Creating additional channel groups");
247             newChannelGroups.addAll(0, thingTypeProvider.getChannelGroupDefinitions(thing.getThingTypeUID()));
248             ThingTypeUID thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_COMPUTER_ID + idExtString);
249             if (thingTypeProvider.updateThingType(thingTypeUID, newChannelGroups)) {
250                 logger.trace("Channel groups were added, changing the thing type");
251                 changeThingType(thingTypeUID, thing.getConfiguration());
252             } else {
253                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR,
254                         "@text/offline.cannot-initialize");
255             }
256             return true;
257         }
258
259         List<Channel> newChannels = new ArrayList<>();
260         newChannels.addAll(createChannels(thingUID, CHANNEL_SENSORS_FAN_SPEED, systeminfo.getFanCount()));
261         if (!newChannels.isEmpty()) {
262             logger.debug("Creating additional channels");
263             newChannels.addAll(0, thing.getChannels());
264             ThingBuilder thingBuilder = editThing();
265             thingBuilder.withChannels(newChannels);
266             updateThing(thingBuilder.build());
267         }
268
269         return false;
270     }
271
272     private List<ChannelGroupDefinition> createChannelGroups(ThingUID thingUID, String channelGroupID,
273             String channelGroupTypeID, int count) {
274         if (count <= 1) {
275             return Collections.emptyList();
276         }
277
278         List<String> channelGroups = thingTypeProvider.getChannelGroupDefinitions(thing.getThingTypeUID()).stream()
279                 .map(ChannelGroupDefinition::getId).collect(Collectors.toList());
280
281         List<ChannelGroupDefinition> newChannelGroups = new ArrayList<>();
282         for (int i = 0; i < count; i++) {
283             String index = String.valueOf(i);
284             ChannelGroupDefinition channelGroupDef = thingTypeProvider
285                     .createChannelGroupDefinitionWithIndex(channelGroupID, channelGroupTypeID, i);
286             if (!(channelGroupDef == null || channelGroups.contains(channelGroupID + index))) {
287                 logger.trace("Adding channel group {}", channelGroupID + index);
288                 newChannelGroups.add(channelGroupDef);
289             }
290         }
291         return newChannelGroups;
292     }
293
294     private List<Channel> createChannels(ThingUID thingUID, String channelID, int count) {
295         if (count <= 1) {
296             return Collections.emptyList();
297         }
298
299         List<Channel> newChannels = new ArrayList<>();
300         for (int i = 0; i < count; i++) {
301             Channel channel = thingTypeProvider.createChannelWithIndex(thing, channelID, i);
302             if (channel != null && thing.getChannel(channel.getUID()) == null) {
303                 logger.trace("Creating channel {}", channel.getUID().getId());
304                 newChannels.add(channel);
305             }
306         }
307         return newChannels;
308     }
309
310     private void storeChannelsConfig() {
311         logger.trace("Storing channel configurations");
312         thingTypeProvider.storeChannelsConfig(thing);
313     }
314
315     private void restoreChannelsConfig() {
316         logger.trace("Restoring channel configurations");
317         Map<String, Configuration> channelsConfig = thingTypeProvider.restoreChannelsConfig(thing.getUID());
318         for (String channelId : channelsConfig.keySet()) {
319             Channel channel = thing.getChannel(channelId);
320             Configuration config = channelsConfig.get(channelId);
321             if (channel != null && config != null) {
322                 Configuration currentConfig = channel.getConfiguration();
323                 for (String param : config.keySet()) {
324                     if (isConfigurationKeyChanged(currentConfig, config, param)) {
325                         handleChannelConfigurationChange(channel, config, param);
326                     }
327                 }
328             }
329         }
330     }
331
332     private void groupChannelsByPriority() {
333         logger.trace("Grouping channels by priority");
334         List<Channel> channels = this.thing.getChannels();
335
336         for (Channel channel : channels) {
337             Configuration properties = channel.getConfiguration();
338             String priority = (String) properties.get(PRIOIRITY_PARAM);
339             if (priority == null) {
340                 logger.debug("Channel with UID {} will not be updated. The channel has no priority set!",
341                         channel.getUID());
342                 break;
343             }
344             switch (priority) {
345                 case "High":
346                     highPriorityChannels.add(channel.getUID());
347                     break;
348                 case "Medium":
349                     mediumPriorityChannels.add(channel.getUID());
350                     break;
351                 case "Low":
352                     lowPriorityChannels.add(channel.getUID());
353                     break;
354                 default:
355                     logger.debug("Invalid priority configuration parameter. Channel will not be updated!");
356             }
357         }
358     }
359
360     private void changeChannelPriority(ChannelUID channelUID, String priority) {
361         switch (priority) {
362             case "High":
363                 mediumPriorityChannels.remove(channelUID);
364                 lowPriorityChannels.remove(channelUID);
365                 highPriorityChannels.add(channelUID);
366                 break;
367             case "Medium":
368                 lowPriorityChannels.remove(channelUID);
369                 highPriorityChannels.remove(channelUID);
370                 mediumPriorityChannels.add(channelUID);
371                 break;
372             case "Low":
373                 highPriorityChannels.remove(channelUID);
374                 mediumPriorityChannels.remove(channelUID);
375                 lowPriorityChannels.add(channelUID);
376                 break;
377             default:
378                 logger.debug("Invalid priority configuration parameter. Channel will not be updated!");
379         }
380     }
381
382     private void scheduleUpdates() {
383         logger.debug("Schedule high priority tasks at fixed rate {} s", refreshIntervalHighPriority);
384         highPriorityTasks = scheduler.scheduleWithFixedDelay(() -> {
385             publishData(highPriorityChannels);
386         }, WAIT_TIME_CHANNEL_ITEM_LINK_INIT, refreshIntervalHighPriority.intValue(), TimeUnit.SECONDS);
387
388         logger.debug("Schedule medium priority tasks at fixed rate {} s", refreshIntervalMediumPriority);
389         mediumPriorityTasks = scheduler.scheduleWithFixedDelay(() -> {
390             publishData(mediumPriorityChannels);
391         }, WAIT_TIME_CHANNEL_ITEM_LINK_INIT, refreshIntervalMediumPriority.intValue(), TimeUnit.SECONDS);
392
393         logger.debug("Schedule one time update for low priority tasks");
394         scheduler.schedule(() -> {
395             publishData(lowPriorityChannels);
396         }, WAIT_TIME_CHANNEL_ITEM_LINK_INIT, TimeUnit.SECONDS);
397     }
398
399     private void publishData(Set<ChannelUID> channels) {
400         // if handler disposed while waiting for the links, don't update the channel states
401         if (!ThingStatus.ONLINE.equals(thing.getStatus())) {
402             return;
403         }
404         Iterator<ChannelUID> iter = channels.iterator();
405         while (iter.hasNext()) {
406             ChannelUID channeUID = iter.next();
407             if (isLinked(channeUID.getId())) {
408                 publishDataForChannel(channeUID);
409             }
410         }
411     }
412
413     private void publishDataForChannel(ChannelUID channelUID) {
414         State state = getInfoForChannel(channelUID);
415         String channelID = channelUID.getId();
416         updateState(channelID, state);
417     }
418
419     public Set<ChannelUID> getHighPriorityChannels() {
420         return highPriorityChannels;
421     }
422
423     public Set<ChannelUID> getMediumPriorityChannels() {
424         return mediumPriorityChannels;
425     }
426
427     public Set<ChannelUID> getLowPriorityChannels() {
428         return lowPriorityChannels;
429     }
430
431     /**
432      * This method gets the information for specific channel through the {@link SysteminfoInterface}. It uses the
433      * channel ID to call the correct method from the {@link SysteminfoInterface} with deviceIndex parameter (in case of
434      * multiple devices, for reference see {@link #getDeviceIndex(String)}})
435      *
436      * @param channelUID the UID of the channel
437      * @return State object or null, if there is no information for the device with this index
438      */
439     private State getInfoForChannel(ChannelUID channelUID) {
440         State state = null;
441
442         String channelID = channelUID.getId();
443         int deviceIndex = getDeviceIndex(channelUID);
444
445         logger.trace("Getting state for channel {} with device index {}", channelID, deviceIndex);
446
447         // The channelGroup or channel may contain deviceIndex. It must be deleted from the channelID, because otherwise
448         // the switch will not find the correct method below.
449         // All digits are deleted from the ID, except for CpuLoad channels.
450         if (!(CHANNEL_CPU_LOAD_1.equals(channelID) || CHANNEL_CPU_LOAD_5.equals(channelID)
451                 || CHANNEL_CPU_LOAD_15.equals(channelID))) {
452             channelID = channelID.replaceAll("\\d+", "");
453         }
454
455         try {
456             switch (channelID) {
457                 case CHANNEL_MEMORY_HEAP_AVAILABLE:
458                     state = new QuantityType<>(Runtime.getRuntime().freeMemory(), Units.BYTE);
459                     break;
460                 case CHANNEL_MEMORY_USED_HEAP_PERCENT:
461                     state = new QuantityType<>((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())
462                             * 100 / Runtime.getRuntime().maxMemory(), Units.PERCENT);
463                     break;
464                 case CHANNEL_DISPLAY_INFORMATION:
465                     state = systeminfo.getDisplayInformation(deviceIndex);
466                     break;
467                 case CHANNEL_BATTERY_NAME:
468                     state = systeminfo.getBatteryName(deviceIndex);
469                     break;
470                 case CHANNEL_BATTERY_REMAINING_CAPACITY:
471                     state = new QuantityType<>(systeminfo.getBatteryRemainingCapacity(deviceIndex), Units.PERCENT);
472                     break;
473                 case CHANNEL_BATTERY_REMAINING_TIME:
474                     state = systeminfo.getBatteryRemainingTime(deviceIndex);
475                     break;
476                 case CHANNEL_SENSORS_CPU_TEMPERATURE:
477                     state = systeminfo.getSensorsCpuTemperature();
478                     break;
479                 case CHANNEL_SENOSRS_CPU_VOLTAGE:
480                     state = systeminfo.getSensorsCpuVoltage();
481                     break;
482                 case CHANNEL_SENSORS_FAN_SPEED:
483                     state = systeminfo.getSensorsFanSpeed(deviceIndex);
484                     break;
485                 case CHANNEL_CPU_LOAD:
486                     PercentType cpuLoad = cpuLoadCache.getValue();
487                     state = (cpuLoad != null) ? new QuantityType<>(cpuLoad, Units.PERCENT) : null;
488                     break;
489                 case CHANNEL_CPU_LOAD_1:
490                     state = systeminfo.getCpuLoad1();
491                     break;
492                 case CHANNEL_CPU_LOAD_5:
493                     state = systeminfo.getCpuLoad5();
494                     break;
495                 case CHANNEL_CPU_LOAD_15:
496                     state = systeminfo.getCpuLoad15();
497                     break;
498                 case CHANNEL_CPU_UPTIME:
499                     state = systeminfo.getCpuUptime();
500                     break;
501                 case CHANNEL_CPU_THREADS:
502                     state = systeminfo.getCpuThreads();
503                     break;
504                 case CHANNEL_CPU_DESCRIPTION:
505                     state = systeminfo.getCpuDescription();
506                     break;
507                 case CHANNEL_CPU_NAME:
508                     state = systeminfo.getCpuName();
509                     break;
510                 case CHANNEL_MEMORY_AVAILABLE:
511                     state = systeminfo.getMemoryAvailable();
512                     break;
513                 case CHANNEL_MEMORY_USED:
514                     state = systeminfo.getMemoryUsed();
515                     break;
516                 case CHANNEL_MEMORY_TOTAL:
517                     state = systeminfo.getMemoryTotal();
518                     break;
519                 case CHANNEL_MEMORY_AVAILABLE_PERCENT:
520                     PercentType memoryAvailablePercent = systeminfo.getMemoryAvailablePercent();
521                     state = (memoryAvailablePercent != null) ? new QuantityType<>(memoryAvailablePercent, Units.PERCENT)
522                             : null;
523                     break;
524                 case CHANNEL_MEMORY_USED_PERCENT:
525                     PercentType memoryUsedPercent = systeminfo.getMemoryUsedPercent();
526                     state = (memoryUsedPercent != null) ? new QuantityType<>(memoryUsedPercent, Units.PERCENT) : null;
527                     break;
528                 case CHANNEL_SWAP_AVAILABLE:
529                     state = systeminfo.getSwapAvailable();
530                     break;
531                 case CHANNEL_SWAP_USED:
532                     state = systeminfo.getSwapUsed();
533                     break;
534                 case CHANNEL_SWAP_TOTAL:
535                     state = systeminfo.getSwapTotal();
536                     break;
537                 case CHANNEL_SWAP_AVAILABLE_PERCENT:
538                     PercentType swapAvailablePercent = systeminfo.getSwapAvailablePercent();
539                     state = (swapAvailablePercent != null) ? new QuantityType<>(swapAvailablePercent, Units.PERCENT)
540                             : null;
541                     break;
542                 case CHANNEL_SWAP_USED_PERCENT:
543                     PercentType swapUsedPercent = systeminfo.getSwapUsedPercent();
544                     state = (swapUsedPercent != null) ? new QuantityType<>(swapUsedPercent, Units.PERCENT) : null;
545                     break;
546                 case CHANNEL_DRIVE_MODEL:
547                     state = systeminfo.getDriveModel(deviceIndex);
548                     break;
549                 case CHANNEL_DRIVE_SERIAL:
550                     state = systeminfo.getDriveSerialNumber(deviceIndex);
551                     break;
552                 case CHANNEL_DRIVE_NAME:
553                     state = systeminfo.getDriveName(deviceIndex);
554                     break;
555                 case CHANNEL_STORAGE_NAME:
556                     state = systeminfo.getStorageName(deviceIndex);
557                     break;
558                 case CHANNEL_STORAGE_DESCRIPTION:
559                     state = systeminfo.getStorageDescription(deviceIndex);
560                     break;
561                 case CHANNEL_STORAGE_AVAILABLE:
562                     state = systeminfo.getStorageAvailable(deviceIndex);
563                     break;
564                 case CHANNEL_STORAGE_USED:
565                     state = systeminfo.getStorageUsed(deviceIndex);
566                     break;
567                 case CHANNEL_STORAGE_TOTAL:
568                     state = systeminfo.getStorageTotal(deviceIndex);
569                     break;
570                 case CHANNEL_STORAGE_TYPE:
571                     state = systeminfo.getStorageType(deviceIndex);
572                     break;
573                 case CHANNEL_STORAGE_AVAILABLE_PERCENT:
574                     PercentType storageAvailablePercent = systeminfo.getStorageAvailablePercent(deviceIndex);
575                     state = (storageAvailablePercent != null)
576                             ? new QuantityType<>(storageAvailablePercent, Units.PERCENT)
577                             : null;
578                     break;
579                 case CHANNEL_STORAGE_USED_PERCENT:
580                     PercentType storageUsedPercent = systeminfo.getStorageUsedPercent(deviceIndex);
581                     state = (storageUsedPercent != null) ? new QuantityType<>(storageUsedPercent, Units.PERCENT) : null;
582                     break;
583                 case CHANNEL_NETWORK_IP:
584                     state = systeminfo.getNetworkIp(deviceIndex);
585                     break;
586                 case CHANNEL_NETWORK_ADAPTER_NAME:
587                     state = systeminfo.getNetworkDisplayName(deviceIndex);
588                     break;
589                 case CHANNEL_NETWORK_NAME:
590                     state = systeminfo.getNetworkName(deviceIndex);
591                     break;
592                 case CHANNEL_NETWORK_MAC:
593                     state = systeminfo.getNetworkMac(deviceIndex);
594                     break;
595                 case CHANNEL_NETWORK_DATA_SENT:
596                     state = systeminfo.getNetworkDataSent(deviceIndex);
597                     break;
598                 case CHANNEL_NETWORK_DATA_RECEIVED:
599                     state = systeminfo.getNetworkDataReceived(deviceIndex);
600                     break;
601                 case CHANNEL_NETWORK_PACKETS_RECEIVED:
602                     state = systeminfo.getNetworkPacketsReceived(deviceIndex);
603                     break;
604                 case CHANNEL_NETWORK_PACKETS_SENT:
605                     state = systeminfo.getNetworkPacketsSent(deviceIndex);
606                     break;
607                 case CHANNEL_PROCESS_LOAD:
608                 case CHANNEL_CURRENT_PROCESS_LOAD:
609                     DecimalType processLoad = processLoadCache.putIfAbsentAndGet(deviceIndex,
610                             () -> getProcessCpuUsage(deviceIndex));
611                     state = (processLoad != null) ? new QuantityType<>(processLoad, Units.PERCENT) : null;
612                     break;
613                 case CHANNEL_PROCESS_MEMORY:
614                 case CHANNEL_CURRENT_PROCESS_MEMORY:
615                     state = systeminfo.getProcessMemoryUsage(deviceIndex);
616                     break;
617                 case CHANNEL_PROCESS_NAME:
618                 case CHANNEL_CURRENT_PROCESS_NAME:
619                     state = systeminfo.getProcessName(deviceIndex);
620                     break;
621                 case CHANNEL_PROCESS_PATH:
622                 case CHANNEL_CURRENT_PROCESS_PATH:
623                     state = systeminfo.getProcessPath(deviceIndex);
624                     break;
625                 case CHANNEL_PROCESS_THREADS:
626                 case CHANNEL_CURRENT_PROCESS_THREADS:
627                     state = systeminfo.getProcessThreads(deviceIndex);
628                     break;
629                 default:
630                     logger.debug("Channel with unknown ID: {} !", channelID);
631             }
632         } catch (DeviceNotFoundException e) {
633             logger.warn("No information for channel {} with device index: {}", channelID, deviceIndex);
634         } catch (Exception e) {
635             logger.debug("Unexpected error occurred while getting system information!", e);
636             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "@text/offline.unexpected-error");
637         }
638         return state != null ? state : UnDefType.UNDEF;
639     }
640
641     private @Nullable PercentType getSystemCpuLoad() {
642         return systeminfo.getSystemCpuLoad();
643     }
644
645     private @Nullable DecimalType getProcessCpuUsage(int pid) {
646         try {
647             return systeminfo.getProcessCpuUsage(pid);
648         } catch (DeviceNotFoundException e) {
649             logger.warn("Process with pid {} does not exist", pid);
650             return null;
651         }
652     }
653
654     /**
655      * The device index is an optional part of the channelID - the last characters of the groupID. It is used to
656      * identify unique device, when more than one devices are available (e.g. local disks with names C:\, D:\, E"\ - the
657      * first will have deviceIndex=0, the second deviceIndex=1 ant etc).
658      * When no device index is specified, default value of 0 (first device in the list) is returned.
659      *
660      * @param channelID the ID of the channel
661      * @return natural number (number >=0)
662      */
663     private int getDeviceIndex(ChannelUID channelUID) {
664         String channelID = channelUID.getId();
665         String channelGroupID = channelUID.getGroupId();
666         if (channelGroupID == null) {
667             return 0;
668         }
669
670         if (channelGroupID.contains(CHANNEL_GROUP_PROCESS)) {
671             // Only in this case the deviceIndex is part of the channel configuration - PID (Process Identifier)
672             int pid = getPID(channelUID);
673             logger.debug("Channel with UID {} tracks process with PID: {}", channelUID, pid);
674             return pid;
675         }
676
677         if (channelGroupID.contains(CHANNEL_GROUP_CURRENT_PROCESS)) {
678             int pid = systeminfo.getCurrentProcessID();
679             return pid;
680         }
681
682         // First try to get device index in group id, delete all non-digits from id
683         if (Character.isDigit(channelGroupID.charAt(channelGroupID.length() - 1))) {
684             String deviceIndexPart = channelGroupID.replaceAll("\\D+", "");
685             return Integer.parseInt(deviceIndexPart);
686         }
687
688         // If not found, try to find it in channel id, delete all non-digits from id
689         if (Character.isDigit(channelID.charAt(channelID.length() - 1))) {
690             String deviceIndexPart = channelID.replaceAll("\\D+", "");
691             return Integer.parseInt(deviceIndexPart);
692         }
693
694         return 0;
695     }
696
697     /**
698      * This method gets the process identifier (PID) for specific process
699      *
700      * @param channelUID channel unique identifier
701      * @return natural number
702      */
703     private int getPID(ChannelUID channelUID) {
704         int pid = 0;
705         try {
706             Channel channel = this.thing.getChannel(channelUID.getId());
707             if (channel != null) {
708                 Configuration channelProperties = channel.getConfiguration();
709                 BigDecimal pidValue = (BigDecimal) channelProperties.get(PID_PARAM);
710                 if (pidValue == null || pidValue.intValue() < 0) {
711                     throw new IllegalArgumentException("Invalid value for Process Identifier.");
712                 } else {
713                     pid = pidValue.intValue();
714                 }
715             } else {
716                 logger.debug("Channel does not exist! Fall back to default value.");
717             }
718         } catch (ClassCastException e) {
719             logger.debug("Channel configuration cannot be read! Fall back to default value.", e);
720         } catch (IllegalArgumentException e) {
721             logger.debug("PID (Process Identifier) must be positive number. Fall back to default value. ", e);
722         }
723         return pid;
724     }
725
726     @Override
727     public void handleCommand(ChannelUID channelUID, Command command) {
728         if (thing.getStatus().equals(ThingStatus.ONLINE)) {
729             if (command instanceof RefreshType) {
730                 logger.debug("Refresh command received for channel {} !", channelUID);
731                 publishDataForChannel(channelUID);
732             } else {
733                 logger.debug("Unsupported command {} ! Supported commands: REFRESH", command);
734             }
735         } else {
736             logger.debug("Cannot handle command. Thing is not ONLINE.");
737         }
738     }
739
740     private boolean isConfigurationKeyChanged(Configuration currentConfig, Configuration newConfig, String key) {
741         Object currentValue = currentConfig.get(key);
742         Object newValue = newConfig.get(key);
743
744         if (currentValue == null) {
745             return (newValue != null);
746         }
747
748         return !currentValue.equals(newValue);
749     }
750
751     @Override
752     public synchronized void thingUpdated(Thing thing) {
753         logger.trace("About to update thing");
754         boolean isChannelConfigChanged = false;
755
756         List<Channel> channels = thing.getChannels();
757
758         for (Channel channel : channels) {
759             ChannelUID channelUID = channel.getUID();
760             Configuration newChannelConfig = channel.getConfiguration();
761             Channel oldChannel = this.thing.getChannel(channelUID.getId());
762
763             if (oldChannel == null) {
764                 logger.warn("Channel with UID {} cannot be updated, as it cannot be found!", channelUID);
765                 continue;
766             }
767             Configuration currentChannelConfig = oldChannel.getConfiguration();
768
769             if (isConfigurationKeyChanged(currentChannelConfig, newChannelConfig, PRIOIRITY_PARAM)) {
770                 isChannelConfigChanged = true;
771
772                 handleChannelConfigurationChange(oldChannel, newChannelConfig, PRIOIRITY_PARAM);
773
774                 String newPriority = (String) newChannelConfig.get(PRIOIRITY_PARAM);
775                 changeChannelPriority(channelUID, newPriority);
776             }
777
778             if (isConfigurationKeyChanged(currentChannelConfig, newChannelConfig, PID_PARAM)) {
779                 isChannelConfigChanged = true;
780                 handleChannelConfigurationChange(oldChannel, newChannelConfig, PID_PARAM);
781             }
782         }
783
784         if (!(isInitialized() && isChannelConfigChanged)) {
785             super.thingUpdated(thing);
786         }
787     }
788
789     private void handleChannelConfigurationChange(Channel channel, Configuration newConfig, String parameter) {
790         Configuration configuration = channel.getConfiguration();
791         Object oldValue = configuration.get(parameter);
792
793         configuration.put(parameter, newConfig.get(parameter));
794
795         Object newValue = newConfig.get(parameter);
796         logger.debug("Channel with UID {} has changed its {} from {} to {}", channel.getUID(), parameter, oldValue,
797                 newValue);
798         publishDataForChannel(channel.getUID());
799     }
800
801     @Override
802     protected void changeThingType(ThingTypeUID thingTypeUID, Configuration configuration) {
803         storeChannelsConfig();
804         super.changeThingType(thingTypeUID, configuration);
805     }
806
807     private void stopScheduledUpdates() {
808         ScheduledFuture<?> localHighPriorityTasks = highPriorityTasks;
809         if (localHighPriorityTasks != null) {
810             logger.debug("High prioriy tasks will not be run anymore!");
811             localHighPriorityTasks.cancel(true);
812         }
813
814         ScheduledFuture<?> localMediumPriorityTasks = mediumPriorityTasks;
815         if (localMediumPriorityTasks != null) {
816             logger.debug("Medium prioriy tasks will not be run anymore!");
817             localMediumPriorityTasks.cancel(true);
818         }
819     }
820
821     @Override
822     public void dispose() {
823         stopScheduledUpdates();
824     }
825 }