battery.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. // SPDX-FileCopyrightText: GSConnect Developers https://github.com/GSConnect
  2. //
  3. // SPDX-License-Identifier: GPL-2.0-or-later
  4. 'use strict';
  5. const Gio = imports.gi.Gio;
  6. const GLib = imports.gi.GLib;
  7. const GObject = imports.gi.GObject;
  8. const Components = imports.service.components;
  9. const PluginBase = imports.service.plugin;
  10. var Metadata = {
  11. label: _('Battery'),
  12. description: _('Exchange battery information'),
  13. id: 'org.gnome.Shell.Extensions.GSConnect.Plugin.Battery',
  14. incomingCapabilities: [
  15. 'kdeconnect.battery',
  16. 'kdeconnect.battery.request',
  17. ],
  18. outgoingCapabilities: [
  19. 'kdeconnect.battery',
  20. 'kdeconnect.battery.request',
  21. ],
  22. actions: {},
  23. };
  24. /**
  25. * Battery Plugin
  26. * https://github.com/KDE/kdeconnect-kde/tree/master/plugins/battery
  27. */
  28. var Plugin = GObject.registerClass({
  29. GTypeName: 'GSConnectBatteryPlugin',
  30. }, class Plugin extends PluginBase.Plugin {
  31. _init(device) {
  32. super._init(device, 'battery');
  33. // Setup Cache; defaults are 90 minute charge, 1 day discharge
  34. this._chargeState = [54, 0, -1];
  35. this._dischargeState = [864, 0, -1];
  36. this._thresholdLevel = 25;
  37. this.cacheProperties([
  38. '_chargeState',
  39. '_dischargeState',
  40. '_thresholdLevel',
  41. ]);
  42. // Export battery state as GAction
  43. this.__state = new Gio.SimpleAction({
  44. name: 'battery',
  45. parameter_type: new GLib.VariantType('(bsii)'),
  46. state: this.state,
  47. });
  48. this.device.add_action(this.__state);
  49. // Local Battery (UPower)
  50. this._upower = null;
  51. this._sendStatisticsId = this.settings.connect(
  52. 'changed::send-statistics',
  53. this._onSendStatisticsChanged.bind(this)
  54. );
  55. this._onSendStatisticsChanged(this.settings);
  56. }
  57. get charging() {
  58. if (this._charging === undefined)
  59. this._charging = false;
  60. return this._charging;
  61. }
  62. get icon_name() {
  63. let icon;
  64. if (this.level === -1)
  65. return 'battery-missing-symbolic';
  66. else if (this.level === 100)
  67. return 'battery-full-charged-symbolic';
  68. else if (this.level < 3)
  69. icon = 'battery-empty';
  70. else if (this.level < 10)
  71. icon = 'battery-caution';
  72. else if (this.level < 30)
  73. icon = 'battery-low';
  74. else if (this.level < 60)
  75. icon = 'battery-good';
  76. else if (this.level >= 60)
  77. icon = 'battery-full';
  78. if (this.charging)
  79. return `${icon}-charging-symbolic`;
  80. return `${icon}-symbolic`;
  81. }
  82. get level() {
  83. // This is what KDE Connect returns if the remote battery plugin is
  84. // disabled or still being loaded
  85. if (this._level === undefined)
  86. this._level = -1;
  87. return this._level;
  88. }
  89. get time() {
  90. if (this._time === undefined)
  91. this._time = 0;
  92. return this._time;
  93. }
  94. get state() {
  95. return new GLib.Variant(
  96. '(bsii)',
  97. [this.charging, this.icon_name, this.level, this.time]
  98. );
  99. }
  100. cacheLoaded() {
  101. this._initEstimate();
  102. this._sendState();
  103. }
  104. clearCache() {
  105. this._chargeState = [54, 0, -1];
  106. this._dischargeState = [864, 0, -1];
  107. this._thresholdLevel = 25;
  108. this._initEstimate();
  109. }
  110. connected() {
  111. super.connected();
  112. this._requestState();
  113. this._sendState();
  114. }
  115. handlePacket(packet) {
  116. switch (packet.type) {
  117. case 'kdeconnect.battery':
  118. this._receiveState(packet);
  119. break;
  120. case 'kdeconnect.battery.request':
  121. this._sendState();
  122. break;
  123. }
  124. }
  125. _onSendStatisticsChanged() {
  126. if (this.settings.get_boolean('send-statistics'))
  127. this._monitorState();
  128. else
  129. this._unmonitorState();
  130. }
  131. /**
  132. * Recalculate and update the estimated time remaining, but not the rate.
  133. */
  134. _initEstimate() {
  135. let rate, level;
  136. // elision of [rate, time, level]
  137. if (this.charging)
  138. [rate,, level] = this._chargeState;
  139. else
  140. [rate,, level] = this._dischargeState;
  141. if (!Number.isFinite(rate) || rate < 1)
  142. rate = this.charging ? 864 : 90;
  143. if (!Number.isFinite(level) || level < 0)
  144. level = this.level;
  145. // Update the time remaining
  146. if (rate && this.charging)
  147. this._time = Math.floor(rate * (100 - level));
  148. else if (rate && !this.charging)
  149. this._time = Math.floor(rate * level);
  150. this.__state.state = this.state;
  151. }
  152. /**
  153. * Recalculate the (dis)charge rate and update the estimated time remaining.
  154. */
  155. _updateEstimate() {
  156. let rate, time, level;
  157. const newTime = Math.floor(Date.now() / 1000);
  158. const newLevel = this.level;
  159. // Load the state; ensure we have sane values for calculation
  160. if (this.charging)
  161. [rate, time, level] = this._chargeState;
  162. else
  163. [rate, time, level] = this._dischargeState;
  164. if (!Number.isFinite(rate) || rate < 1)
  165. rate = this.charging ? 54 : 864;
  166. if (!Number.isFinite(time) || time <= 0)
  167. time = newTime;
  168. if (!Number.isFinite(level) || level < 0)
  169. level = newLevel;
  170. // Update the rate; use a weighted average to account for missed changes
  171. // NOTE: (rate = seconds/percent)
  172. const ldiff = this.charging ? newLevel - level : level - newLevel;
  173. const tdiff = newTime - time;
  174. const newRate = tdiff / ldiff;
  175. if (newRate && Number.isFinite(newRate))
  176. rate = Math.floor((rate * 0.4) + (newRate * 0.6));
  177. // Store the state for the next recalculation
  178. if (this.charging)
  179. this._chargeState = [rate, newTime, newLevel];
  180. else
  181. this._dischargeState = [rate, newTime, newLevel];
  182. // Update the time remaining
  183. if (rate && this.charging)
  184. this._time = Math.floor(rate * (100 - newLevel));
  185. else if (rate && !this.charging)
  186. this._time = Math.floor(rate * newLevel);
  187. this.__state.state = this.state;
  188. }
  189. /**
  190. * Notify the user the remote battery is full.
  191. */
  192. _fullBatteryNotification() {
  193. if (!this.settings.get_boolean('full-battery-notification'))
  194. return;
  195. // Offer the option to ring the device, if available
  196. let buttons = [];
  197. if (this.device.get_action_enabled('ring')) {
  198. buttons = [{
  199. label: _('Ring'),
  200. action: 'ring',
  201. parameter: null,
  202. }];
  203. }
  204. this.device.showNotification({
  205. id: 'battery|full',
  206. // TRANSLATORS: eg. Google Pixel: Battery is full
  207. title: _('%s: Battery is full').format(this.device.name),
  208. // TRANSLATORS: when the battery is fully charged
  209. body: _('Fully Charged'),
  210. icon: Gio.ThemedIcon.new('battery-full-charged-symbolic'),
  211. buttons: buttons,
  212. });
  213. }
  214. /**
  215. * Notify the user the remote battery is at custom charge level.
  216. */
  217. _customBatteryNotification() {
  218. if (!this.settings.get_boolean('custom-battery-notification'))
  219. return;
  220. // Offer the option to ring the device, if available
  221. let buttons = [];
  222. if (this.device.get_action_enabled('ring')) {
  223. buttons = [{
  224. label: _('Ring'),
  225. action: 'ring',
  226. parameter: null,
  227. }];
  228. }
  229. this.device.showNotification({
  230. id: 'battery|custom',
  231. // TRANSLATORS: eg. Google Pixel: Battery has reached custom charge level
  232. title: _('%s: Battery has reached custom charge level').format(this.device.name),
  233. // TRANSLATORS: when the battery has reached custom charge level
  234. body: _('%d%% Charged').format(this.level),
  235. icon: Gio.ThemedIcon.new('battery-full-charged-symbolic'),
  236. buttons: buttons,
  237. });
  238. }
  239. /**
  240. * Notify the user the remote battery is low.
  241. */
  242. _lowBatteryNotification() {
  243. if (!this.settings.get_boolean('low-battery-notification'))
  244. return;
  245. // Offer the option to ring the device, if available
  246. let buttons = [];
  247. if (this.device.get_action_enabled('ring')) {
  248. buttons = [{
  249. label: _('Ring'),
  250. action: 'ring',
  251. parameter: null,
  252. }];
  253. }
  254. this.device.showNotification({
  255. id: 'battery|low',
  256. // TRANSLATORS: eg. Google Pixel: Battery is low
  257. title: _('%s: Battery is low').format(this.device.name),
  258. // TRANSLATORS: eg. 15% remaining
  259. body: _('%d%% remaining').format(this.level),
  260. icon: Gio.ThemedIcon.new('battery-caution-symbolic'),
  261. buttons: buttons,
  262. });
  263. }
  264. /**
  265. * Handle a remote battery update.
  266. *
  267. * @param {Core.Packet} packet - A kdeconnect.battery packet
  268. */
  269. _receiveState(packet) {
  270. // Charging state changed
  271. this._charging = packet.body.isCharging;
  272. // Level changed
  273. if (this._level !== packet.body.currentCharge) {
  274. this._level = packet.body.currentCharge;
  275. // If the level is above the threshold hide the notification
  276. if (this._level > this._thresholdLevel)
  277. this.device.hideNotification('battery|low');
  278. // The level just changed to/from custom level while charging
  279. if ((this._level === this.settings.get_uint('custom-battery-notification-value')) && this._charging)
  280. this._customBatteryNotification();
  281. else
  282. this.device.hideNotification('battery|custom');
  283. // The level just changed to/from full
  284. if (this._level === 100)
  285. this._fullBatteryNotification();
  286. else
  287. this.device.hideNotification('battery|full');
  288. }
  289. // Device considers the level low
  290. if (packet.body.thresholdEvent > 0) {
  291. this._lowBatteryNotification();
  292. this._thresholdLevel = this.level;
  293. }
  294. this._updateEstimate();
  295. }
  296. /**
  297. * Request the remote battery's current state
  298. */
  299. _requestState() {
  300. this.device.sendPacket({
  301. type: 'kdeconnect.battery.request',
  302. body: {request: true},
  303. });
  304. }
  305. /**
  306. * Report the local battery's current state
  307. */
  308. _sendState() {
  309. if (this._upower === null || !this._upower.is_present)
  310. return;
  311. this.device.sendPacket({
  312. type: 'kdeconnect.battery',
  313. body: {
  314. currentCharge: this._upower.level,
  315. isCharging: this._upower.charging,
  316. thresholdEvent: this._upower.threshold,
  317. },
  318. });
  319. }
  320. /*
  321. * UPower monitoring methods
  322. */
  323. _monitorState() {
  324. try {
  325. // Currently only true if the remote device is a desktop (rare)
  326. const incoming = this.device.settings.get_strv('incoming-capabilities');
  327. if (!incoming.includes('kdeconnect.battery'))
  328. return;
  329. this._upower = Components.acquire('upower');
  330. this._upowerId = this._upower.connect(
  331. 'changed',
  332. this._sendState.bind(this)
  333. );
  334. this._sendState();
  335. } catch (e) {
  336. logError(e, this.device.name);
  337. this._unmonitorState();
  338. }
  339. }
  340. _unmonitorState() {
  341. try {
  342. if (this._upower === null)
  343. return;
  344. this._upower.disconnect(this._upowerId);
  345. this._upower = Components.release('upower');
  346. } catch (e) {
  347. logError(e, this.device.name);
  348. }
  349. }
  350. destroy() {
  351. this.device.remove_action('battery');
  352. this.settings.disconnect(this._sendStatisticsId);
  353. this._unmonitorState();
  354. super.destroy();
  355. }
  356. });