Compare commits

...

129 Commits

Author SHA1 Message Date
94cc596afa Add git commit to version output 2021-03-10 21:39:47 -06:00
1a7b665376 Use tablewriter for output formatting 2021-03-10 20:57:05 -06:00
2d2efd4431 Move print functions 2021-03-07 10:45:56 -06:00
3c9137816d make make clean silent 2021-03-07 10:33:28 -06:00
40851c6a62 Use terminal color library 2021-03-07 10:32:05 -06:00
518e304948 Add support for nil flag sets 2021-03-03 23:31:27 -06:00
78c7572139 Use parentheses 2021-03-03 00:29:40 -06:00
5b17adb071 Make make output quiet 2021-03-02 20:50:21 -06:00
38ab315a9b Add build date to LDFLAGS 2021-03-02 20:50:21 -06:00
de0bc2e133 Show rumtime information in version output 2021-03-02 00:44:38 -06:00
4d3074fa14 Use LDFLAGS to set build version 2021-03-02 00:44:18 -06:00
c8d0d306e4 Add quiet flag to del 2021-03-02 00:40:22 -06:00
8a7e99234f Add Windows support to Makefile 2021-03-01 22:59:11 -06:00
bfb949ca5f Ignore VSCode logs files 2021-03-01 22:58:25 -06:00
0fac4a3c14 Add version command 2021-02-27 22:42:09 -06:00
c9e4d9af80 Improve command loading 2021-02-16 23:24:32 -06:00
dd0bf763a3 Add PrintfWithIndent function 2021-02-16 20:20:18 -06:00
01086e3c22 Formatting changes for the show command 2021-02-15 19:46:13 -06:00
63bbbcecf7 Add pre-release tag 2021-02-15 19:30:25 -06:00
862b70316f Add MPL-2 licesne file 2021-02-14 23:17:02 -06:00
272ae7cd01 Add show command 2021-02-14 23:06:12 -06:00
cf8b34fe01 Move client library to separate repo
git.kill0.net/chill9/lifx-go
2021-02-14 19:02:26 -06:00
761e38fd8e Add version to user agent 2021-02-13 18:42:47 -06:00
e0a658edf7 Minor change to library user agent 2021-02-13 18:42:07 -06:00
a7fab72a1e Use functional options for the client constructor 2021-02-11 09:16:24 -06:00
b643635cf4 Make the user agent configurable 2021-02-10 22:16:15 -06:00
8e7ff7f39a Validate flags before running the command 2021-02-07 17:38:49 -06:00
8c6567bc8a Using os.Args is not necessary 2021-02-07 17:31:57 -06:00
d8be978ba8 Pass command name to CmdArgs struct 2021-02-07 17:31:19 -06:00
9360df727a Consolidate subcommand registration 2021-02-02 20:25:19 -06:00
4e25579718 Sort commands in help output
Closes #5
2021-02-02 20:24:57 -06:00
0cbd256b86 Print help if no subcommand is given.
Closes #4
2021-01-31 20:31:00 -06:00
9321095e11 Clean up subcommand registrations 2021-01-31 19:40:27 -06:00
320815293d ExitFailure matches stdlib.h 2021-01-31 11:08:24 -06:00
ec673a6fde Return usage error if no color is provided 2021-01-24 20:50:10 -06:00
f2da3dadd7 Whitespace fix 2021-01-24 20:49:22 -06:00
211de24485 Add helper to print subcommand help 2021-01-24 20:48:38 -06:00
743d0eed7c Show error from TOML library when parsing fails 2021-01-24 19:21:54 -06:00
b1894b38de Validate colors from configuration file 2021-01-24 19:21:44 -06:00
1ac9487c76 Add sample colors to sample .lumerc 2021-01-24 19:21:17 -06:00
8364201d7b Add helper method to exit with error code 2021-01-20 23:26:33 -06:00
c3495ac57a Add method to validate configuration 2021-01-20 23:26:33 -06:00
b9e98679a1 Refactor CLI exit code and error handling 2021-01-20 23:26:33 -06:00
c816ee43e1 Fix import alias 2021-01-20 23:26:33 -06:00
2da3bcc2ff Return error codes instead of exiting from Main() 2021-01-20 23:26:33 -06:00
4c6c3744c9 Move lume main into the lumecmd package 2021-01-20 23:26:33 -06:00
84c1be5054 Print error if .lumerc cannot be found 2021-01-20 23:26:32 -06:00
1e4a5f988e Use snake case in the configuration file 2021-01-20 23:26:32 -06:00
e8abc45377 Add poweron and poweroff commands 2021-01-20 23:26:32 -06:00
6e1863f374 Add CLI output sort functions 2021-01-20 23:26:32 -06:00
d0691362d8 Use a map to track column widths 2021-01-20 23:26:32 -06:00
715fb435e1 Refactor configuration file loading 2021-01-20 23:26:31 -06:00
63631be598 Fix composite literal uses unkeyed fields 2021-01-20 23:26:31 -06:00
30fae38ad1 Move Windows console hack into constrained file to fix Linux build 2021-01-20 23:26:31 -06:00
c838c28e49 Add .lumerc to .gitignore 2021-01-20 23:26:31 -06:00
af2721720d Remove __debug_bin 2021-01-20 23:26:27 -06:00
1397fbe4a3 Fix help usage 2021-01-10 21:10:08 -06:00
cd3653deef fix ls command usage text 2021-01-10 21:10:03 -06:00
095c7bd995 Move configuration loading to separate function 2021-01-10 21:09:59 -06:00
9988800431 Enable terminal colors on Windows 10 2021-01-10 21:09:54 -06:00
91478dd20e Add vscode stuff 2021-01-10 21:09:50 -06:00
bd1939e546 Create go module 2021-01-10 21:09:47 -06:00
b834bf84b2 fix syntax 2021-01-10 21:09:36 -06:00
cb87159237 add help command 2020-08-07 22:11:33 -05:00
491870e247 add short and long descriptions of the commands 2020-08-07 22:09:40 -05:00
617c2fccf9 add usage to every command 2020-08-07 18:44:36 -05:00
4325398ca8 add usage information to Command struct 2020-08-07 18:11:42 -05:00
39d889ecb6 add name to Command struct 2020-08-07 18:09:54 -05:00
e373e7e273 add error helpers 2020-04-05 18:54:40 -05:00
7fd366823f remove unused import 2020-04-04 15:30:52 -05:00
5bafaa35e4 remove debug code 2020-04-04 12:19:39 -05:00
cc19b87e39 add Response struct, populate rate limit struct 2020-04-04 12:18:13 -05:00
f8e9dbc716 add named colors via the config file 2020-04-04 10:27:09 -05:00
3a6ee185fb return errors to main() 2020-03-29 00:08:17 -05:00
6b033f10de pass the Config struct to the commands 2020-03-28 23:47:42 -05:00
968b098344 fix incorrect comand name 2020-03-28 23:45:27 -05:00
8b2a67b73b remove dead code 2020-03-28 18:13:15 -05:00
1b054466cf add set-color command 2020-03-28 18:05:35 -05:00
8c0e325447 parse comma separated RGB string 2020-03-28 18:04:53 -05:00
fce5ff9667 fix bug where RGBColor could not be marshalled 2020-03-28 18:04:11 -05:00
bdcb20acb2 returning a pointer is not necessary 2020-03-28 18:03:49 -05:00
4b6f159d03 add float32 flag parser 2020-03-28 18:03:16 -05:00
67cd97e2d8 store CLI defaults into variables 2020-03-28 15:22:34 -05:00
676eabb0cb rename project to lume 2020-03-28 14:31:10 -05:00
9452aec154 fix spelling 2020-03-28 13:29:35 -05:00
04684b0ad6 add set-white command 2020-03-28 13:18:30 -05:00
ca6008db64 add int16 flag parser 2020-03-28 13:18:15 -05:00
4e03e59bad fix kelvin validation range 2020-03-28 13:17:52 -05:00
77c320d2a8 use variables 2020-03-27 19:53:11 -05:00
4ea3545ea7 add set-state command 2020-03-27 19:31:41 -05:00
8df5b1d779 change error format 2020-03-27 19:31:12 -05:00
7c7b06e893 create utils module 2020-03-27 02:01:14 -05:00
e9771c4ca7 add short flags 2020-03-26 22:00:16 -05:00
917053f39c error helpers 2020-03-26 21:05:11 -05:00
bba7c22460 improve error handling 2020-03-26 20:52:11 -05:00
4d496f7524 formatting 2020-03-26 20:51:26 -05:00
7ef6d66564 refactor command line code 2020-03-26 19:05:50 -05:00
6afe13812a fix variable name 2020-03-26 02:16:08 -05:00
079b1a469d refactored command line tool 2020-03-24 19:12:35 -05:00
2283a91ab8 housekeeping 2020-03-24 18:41:56 -05:00
83c96812d7 fix typo 2020-03-24 18:33:22 -05:00
4420c20933 a full ANSI color library is not required yet 2020-03-24 09:14:22 -05:00
25172da555 move ls printing into separate function 2020-03-24 01:35:18 -05:00
f31fc298cd calculate column widths with less looping 2020-03-24 01:31:31 -05:00
7d8e5f8b92 deserialize as time 2020-03-24 00:26:22 -05:00
d3c56d3aa8 add validation to RGBColor 2020-03-24 00:26:06 -05:00
f947b9b1ab add ls to lume 2020-03-24 00:25:46 -05:00
fe40294f52 rename variables 2020-03-22 14:41:54 -05:00
adc8b72e0e add some default color constructors 2020-03-22 14:40:41 -05:00
7773883688 add set-white subcommand 2020-03-22 14:06:14 -05:00
7c27d173f4 refactor white constructors 2020-03-22 11:31:10 -05:00
dc4159550c add new CLI tool called lume 2020-03-14 11:08:12 -05:00
de669f159e remove scratch test cli tool 2020-03-12 16:47:38 -05:00
6a5e6d0753 forgot to add utils file 2020-03-08 13:47:21 -05:00
39a9d377d1 use pointers 2020-03-08 13:47:01 -05:00
73a666a216 make method naming more consistent 2020-03-07 20:06:22 -06:00
05566f480f add SetDelta function 2020-03-07 20:02:37 -06:00
e39d81f6cc add ListLights function 2020-03-06 23:00:21 -06:00
40a7a9d741 refactor client class again 2020-03-06 20:55:31 -06:00
c3b8d84968 there is no JSON response in fast mode 2020-03-06 01:34:28 -06:00
243d0f6f31 refactor SetState function 2020-03-06 01:28:39 -06:00
f58f523d35 handle HTTP statuses 2020-03-06 01:28:12 -06:00
43465c6ae9 extended response struct 2020-03-06 01:27:46 -06:00
3a94226aa8 fix float format string 2020-03-05 20:21:18 -06:00
46991b2ba3 fix up the default named white levels 2020-03-05 20:20:54 -06:00
2da20d6ec7 zero is valid 2020-03-05 20:20:16 -06:00
35a5b99bf4 add default preset white temperatures from the app 2020-03-02 23:52:41 -06:00
888f29383e add User-Agent header 2020-03-01 11:27:26 -06:00
0427121975 add proper Content-Type header 2020-03-01 11:23:59 -06:00
29 changed files with 1687 additions and 392 deletions

4
.gitignore vendored
View File

@ -15,3 +15,7 @@
# Dependency directories (remove the comment below to include it)
# vendor/
.lumerc
.vscode/configurationCache.log
.vscode/dryrun.log
.vscode/targets.log

11
.lumerc.sample Normal file
View File

@ -0,0 +1,11 @@
access_token = "token"
[colors]
purple_candy = [ 280.0, 0.29, 0.71 ]
wasabi = [ 120.0, 1.0, 0.7 ]
honeydew = [ 120.0, 1.0, 0.97 ]
green_mist = [ 92.0, 0.72, 0.75 ]
pea = [ 90.0, 0.42, 0.47 ]
cat_eye = [ 76.0, 0.74, 0.61 ]
seagreen = [ 160.0, 1.0, 0.50 ]
blue_mist = [ 202.0, 0.97, 0.75 ]

15
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,15 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}/cmd/lume"
}
]
}

23
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,23 @@
{
"version": "2.0.0",
"type": "shell",
"command": "go",
"cwd": "${workspaceFolder}",
"tasks": [
{
"label": "install",
"args": ["install", "-v", "./..."],
"group": "build",
},
{
"label": "run",
"args": ["run", "${file}"],
"group": "build",
},
{
"label": "test",
"args": ["test", "-v", "./..."],
"group": "test",
},
],
}

312
LICENSE Normal file
View File

@ -0,0 +1,312 @@
Mozilla Public License Version 2.0
1. Definitions
1.1. "Contributor" means each individual or legal entity that creates, contributes
to the creation of, or owns Covered Software.
1.2. "Contributor Version" means the combination of the Contributions of others
(if any) used by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution" means Covered Software of a particular Contributor.
1.4. "Covered Software" means Source Code Form to which the initial Contributor
has attached the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case including portions
thereof.
1.5. "Incompatible With Secondary Licenses" means
(a) that the initial Contributor has attached the notice described in Exhibit
B to the Covered Software; or
(b) that the Covered Software was made available under the terms of version
1.1 or earlier of the License, but not also under the terms of a Secondary
License.
1.6. "Executable Form" means any form of the work other than Source Code Form.
1.7. "Larger Work" means a work that combines Covered Software with other
material, in a separate file or files, that is not Covered Software.
1.8. "License" means this document.
1.9. "Licensable" means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and all of the
rights conveyed by this License.
1.10. "Modifications" means any of the following:
(a) any file in Source Code Form that results from an addition to, deletion
from, or modification of the contents of Covered Software; or
(b) any new file in Source Code Form that contains any Covered Software.
1.11. "Patent Claims" of a Contributor means any patent claim(s), including
without limitation, method, process, and apparatus claims, in any patent Licensable
by such Contributor that would be infringed, but for the grant of the License,
by the making, using, selling, offering for sale, having made, import, or
transfer of either its Contributions or its Contributor Version.
1.12. "Secondary License" means either the GNU General Public License, Version
2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those licenses.
1.13. "Source Code Form" means the form of the work preferred for making modifications.
1.14. "You" (or "Your") means an individual or a legal entity exercising rights
under this License. For legal entities, "You" includes any entity that controls,
is controlled by, or is under common control with You. For purposes of this
definition, "control" means (a) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or otherwise,
or (b) ownership of more than fifty percent (50%) of the outstanding shares
or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive
license:
(a) under intellectual property rights (other than patent or trademark) Licensable
by such Contributor to use, reproduce, make available, modify, display, perform,
distribute, and otherwise exploit its Contributions, either on an unmodified
basis, with Modifications, or as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its Contributions or
its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution become
effective for each Contribution on the date the Contributor first distributes
such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under this
License. No additional rights or licenses will be implied from the distribution
or licensing of Covered Software under this License. Notwithstanding Section
2.1(b) above, no patent license is granted by a Contributor:
(a) for any code that a Contributor has removed from Covered Software; or
(b) for infringements caused by: (i) Your and any other third party's modifications
of Covered Software, or (ii) the combination of its Contributions with other
software (except as part of its Contributor Version); or
(c) under Patent Claims infringed by Covered Software in the absence of its
Contributions.
This License does not grant any rights in the trademarks, service marks, or
logos of any Contributor (except as may be necessary to comply with the notice
requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to distribute
the Covered Software under a subsequent version of this License (see Section
10.2) or under the terms of a Secondary License (if permitted under the terms
of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its Contributions
are its original creation(s) or it has sufficient rights to grant the rights
to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under applicable
copyright doctrines of fair use, fair dealing, or other equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any Modifications
that You create or to which You contribute, must be under the terms of this
License. You must inform recipients that the Source Code Form of the Covered
Software is governed by the terms of this License, and how they can obtain
a copy of this License. You may not attempt to alter or restrict the recipients'
rights in the Source Code Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the Executable
Form how they can obtain a copy of such Source Code Form by reasonable means
in a timely manner, at a charge no more than the cost of distribution to the
recipient; and
(b) You may distribute such Executable Form under the terms of this License,
or sublicense it under different terms, provided that the license for the
Executable Form does not attempt to limit or alter the recipients' rights
in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice, provided
that You also comply with the requirements of this License for the Covered
Software. If the Larger Work is a combination of Covered Software with a work
governed by one or more Secondary Licenses, and the Covered Software is not
Incompatible With Secondary Licenses, this License permits You to additionally
distribute such Covered Software under the terms of such Secondary License(s),
so that the recipient of the Larger Work may, at their option, further distribute
the Covered Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices (including
copyright notices, patent notices, disclaimers of warranty, or limitations
of liability) contained within the Source Code Form of the Covered Software,
except that You may alter any license notices to the extent required to remedy
known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support, indemnity
or liability obligations to one or more recipients of Covered Software. However,
You may do so only on Your own behalf, and not on behalf of any Contributor.
You must make it absolutely clear that any such warranty, support, indemnity,
or liability obligation is offered by You alone, and You hereby agree to indemnify
every Contributor for any liability incurred by such Contributor as a result
of warranty, support, indemnity or liability terms You offer. You may include
additional disclaimers of warranty and limitations of liability specific to
any jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute, judicial
order, or regulation then You must: (a) comply with the terms of this License
to the maximum extent possible; and (b) describe the limitations and the code
they affect. Such description must be placed in a text file included with
all distributions of the Covered Software under this License. Except to the
extent prohibited by statute or regulation, such description must be sufficiently
detailed for a recipient of ordinary skill to be able to understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if
You fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor are
reinstated (a) provisionally, unless and until such Contributor explicitly
and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor
fails to notify You of the non-compliance by some reasonable means prior to
60 days after You have come back into compliance. Moreover, Your grants from
a particular Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the first
time You have received notice of non-compliance with this License from such
Contributor, and You become compliant prior to 30 days after Your receipt
of the notice.
5.2. If You initiate litigation against any entity by asserting a patent infringement
claim (excluding declaratory judgment actions, counter-claims, and cross-claims)
alleging that a Contributor Version directly or indirectly infringes any patent,
then the rights granted to You by any and all Contributors for the Covered
Software under Section 2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end
user license agreements (excluding distributors and resellers) which have
been validly granted by You or Your distributors under this License prior
to termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an "as is" basis, without
warranty of any kind, either expressed, implied, or statutory, including,
without limitation, warranties that the Covered Software is free of defects,
merchantable, fit for a particular purpose or non-infringing. The entire risk
as to the quality and performance of the Covered Software is with You. Should
any Covered Software prove defective in any respect, You (not any Contributor)
assume the cost of any necessary servicing, repair, or correction. This disclaimer
of warranty constitutes an essential part of this License. No use of any Covered
Software is authorized under this License except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any character
including, without limitation, damages for lost profits, loss of goodwill,
work stoppage, computer failure or malfunction, or any and all other commercial
damages or losses, even if such party shall have been informed of the possibility
of such damages. This limitation of liability shall not apply to liability
for death or personal injury resulting from such party's negligence to the
extent applicable law prohibits such limitation. Some jurisdictions do not
allow the exclusion or limitation of incidental or consequential damages,
so this exclusion and limitation may not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts
of a jurisdiction where the defendant maintains its principal place of business
and such litigation shall be governed by laws of that jurisdiction, without
reference to its conflict-of-law provisions. Nothing in this Section shall
prevent a party's ability to bring cross-claims or counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject matter
hereof. If any provision of this License is held to be unenforceable, such
provision shall be reformed only to the extent necessary to make it enforceable.
Any law or regulation which provides that the language of a contract shall
be construed against the drafter shall not be used to construe this License
against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section 10.3,
no one other than the license steward has the right to modify or publish new
versions of this License. Each version will be given a distinguishing version
number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version of
the License under which You originally received the Covered Software, or under
the terms of any subsequent version published by the license steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to create
a new license for such software, you may create and use a modified version
of this License if you rename the license and remove any references to the
name of the license steward (except to note that such modified license differs
from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With Secondary
Licenses under the terms of this version of the License, the notice described
in Exhibit B of this License must be attached. Exhibit A - Source Code Form
License Notice
This Source Code Form is subject to the terms of the Mozilla Public License,
v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file,
then You may include the notice in a location (such as a LICENSE file in a
relevant directory) where a recipient would be likely to look for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible With Secondary Licenses", as defined
by the Mozilla Public License, v. 2.0.

View File

@ -1,7 +1,27 @@
V ?= 0
Q = $(if $(filter 1, $V),, @)
ifeq ($(OS), Windows_NT)
EXE=lume.exe
RM=del /f /q
BUILD_DATE=$(shell powershell Get-Date -Format "yyyy-MM-ddThh:mm:sszzz")
else
EXE=lume
EXE=rm -f
BUILD_DATE=$(shell date --iso-8601=seconds)
endif
LUME_VERSION ?= $(shell git describe --tags --always)
GIT_COMMIT := $(shell git rev-parse --short HEAD)
LDFLAGS := $(LDFLAGS) \
-X git.kill0.net/chill9/lume/cmd.Version=$(LUME_VERSION) \
-X git.kill0.net/chill9/lume/cmd.BuildDate=$(BUILD_DATE) \
-X git.kill0.net/chill9/lume/cmd.GitCommit=$(GIT_COMMIT)
.PHONY: build
build:
go build -o lifx ./cmd
$(Q) go build -o $(EXE) -ldflags="$(LDFLAGS)" ./cmd/lume
.PHONY: clean
clean:
rm -f ./lifx
$(Q) $(RM) $(EXE)

View File

@ -1,98 +0,0 @@
package lifx
import (
//"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
)
type (
Client struct {
accessToken string
Client *http.Client
}
Results struct {
Results []Result `json:results`
}
Result struct {
ID string `json:"id"`
Label string `json:"label"`
Status Status `json:"status"`
}
)
var errorMap = map[int]error{
http.StatusNotFound: errors.New("Selector did not match any lights"),
http.StatusUnauthorized: errors.New("Bad access token"),
http.StatusForbidden: errors.New("Bad OAuth scope"),
http.StatusUnprocessableEntity: errors.New("Missing or malformed parameters"),
http.StatusUpgradeRequired: errors.New("HTTP was used to make the request instead of HTTPS. Repeat the request using HTTPS instead"),
http.StatusTooManyRequests: errors.New("The request exceeded a rate limit"),
http.StatusInternalServerError: errors.New("Something went wrong on LIFX's end"),
http.StatusBadGateway: errors.New("Something went wrong on LIFX's end"),
http.StatusServiceUnavailable: errors.New("Something went wrong on LIFX's end"),
523: errors.New("Something went wrong on LIFX's end"),
}
func NewClient(accessToken string) *Client {
tr := &http.Transport{
//TLSNextProto: make(map[string]func(authority string, c *tls.Conn) http.RoundTripper),
}
return &Client{
accessToken: accessToken,
Client: &http.Client{Transport: tr},
}
}
func (c *Client) NewRequest(method, url string, body io.Reader) (req *http.Request, err error) {
req, err = http.NewRequest(method, url, body)
if err != nil {
return
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.accessToken))
return
}
func (c *Client) Request(method, url string, body io.Reader) (*http.Response, error) {
req, err := c.NewRequest(method, url, body)
if err != nil {
return nil, err
}
resp, err := c.Client.Do(req)
if err != nil {
return nil, err
}
switch resp.StatusCode {
case http.StatusOK, http.StatusAccepted, http.StatusMultiStatus:
return resp, nil
}
err, ok := errorMap[resp.StatusCode]
if ok {
return resp, err
}
return resp, nil
}
func (c *Client) UnmarshalResponse(resp *http.Response, s interface{}) error {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, &s)
if err != nil {
return err
}
return nil
}

133
cmd/command.go Normal file
View File

@ -0,0 +1,133 @@
package lumecmd
import (
"errors"
"flag"
"fmt"
"strconv"
"git.kill0.net/chill9/lifx-go"
)
const (
ExitSuccess = iota
ExitFailure
)
type Config struct {
AccessToken string `toml:"access_token"`
OutputFormat string `toml:"output_format"`
Colors map[string][]float32 `toml:"colors"`
}
type CmdArgs struct {
Flags Flags
Args []string
Client *lifx.Client
Config Config
Name string
}
type Flags struct {
*flag.FlagSet
}
type Command struct {
Name string
Func func(CmdArgs) (int, error)
Flags *flag.FlagSet
Use string
Short string
Long string
}
var commandRegistry = make(map[string]Command)
var (
defaultSelector string = "all"
defaultDuration float64 = 1.0
defaultPower string = ""
defaultColor string = ""
defaultBrightness string = ""
defaultInfrared string = ""
defaultFast bool = false
defaultWhiteKelvin string = ""
defaultWhiteName string = ""
defaultHue string = ""
defaultSaturation string = ""
defaultRGB string = ""
defaultName string = ""
defaultOutputFormat string = ""
)
func (f Flags) String(name string) string {
return f.FlagSet.Lookup(name).Value.String()
}
func (f Flags) Float32(name string) float32 {
val, _ := strconv.ParseFloat(f.String(name), 32)
return float32(val)
}
func (f Flags) Float64(name string) float64 {
val, _ := strconv.ParseFloat(f.String(name), 64)
return val
}
func (f Flags) Int16(name string) int16 {
val, _ := strconv.ParseInt(f.String(name), 10, 16)
return int16(val)
}
func (f Flags) Bool(name string) bool {
val, _ := strconv.ParseBool(f.String(name))
return val
}
func RegisterCommand(cmd Command) error {
if _, ok := commandRegistry[cmd.Name]; ok {
return fmt.Errorf("%s command is already registered")
}
commandRegistry[cmd.Name] = cmd
return nil
}
func GetCommand(name string) (Command, bool) {
cmd, ok := commandRegistry[name]
return cmd, ok
}
// Validate configuration struct
func (c *Config) Validate() error {
var err error
if c.AccessToken == "" {
err = errors.New("access_token is not set")
}
if err = c.validateColors(); err != nil {
return err
}
return err
}
func (c *Config) validateColors() (err error) {
if len(c.Colors) > 0 {
for name, hsb := range c.Colors {
if len(hsb) != 3 {
return fmt.Errorf("color '%s' needs three values", name)
}
h, s, b := hsb[0], hsb[1], hsb[2]
if h < 0 || h > 360 {
return fmt.Errorf("color '%s' hue value must be between 0.0-360.0", name)
}
if s < 0 || b > 1 {
return fmt.Errorf("color '%s' saturation value must be between 0.0-1.0", name)
}
if b < 0 || b > 1 {
return fmt.Errorf("color '%s' brightness value must be between 0.0-1.0", name)
}
}
}
return err
}

69
cmd/help.go Normal file
View File

@ -0,0 +1,69 @@
package lumecmd
import (
"fmt"
"sort"
)
func NewCmdHelp() Command {
return Command{
Name: "help",
Func: HelpCmd,
Use: "<command>",
Short: "Show help for a command",
}
}
func HelpCmd(args CmdArgs) (int, error) {
if len(args.Args) == 0 {
printHelp(commandRegistry)
} else if len(args.Args) >= 1 {
printCmdHelp(args.Args[0])
}
return ExitSuccess, nil
}
func printHelp(commands map[string]Command) {
var maxLen, cmdLen int
var keys []string
for _, c := range commands {
keys = append(keys, c.Name)
cmdLen = len(c.Name)
if cmdLen > maxLen {
maxLen = cmdLen
}
}
fmt.Printf("usage:\n lume <command> [<args...>]")
fmt.Println()
fmt.Println("\ncommands:")
sort.Strings(keys)
for _, k := range keys {
c := commands[k]
fmt.Printf(" %-*s %s\n", maxLen, c.Name, c.Short)
}
}
func printCmdHelp(name string) error {
subCmd, ok := commandRegistry[name]
if !ok {
return fmt.Errorf("unknown commnnd: %s\n", name)
}
if subCmd.Use != "" {
fmt.Printf("usage:\n lume %s %s\n", subCmd.Name, subCmd.Use)
} else {
fmt.Printf("usage:\n lume %s\n", subCmd.Name)
}
if subCmd.Flags != nil {
fmt.Println()
fmt.Print("flags:\n")
subCmd.Flags.PrintDefaults()
}
return nil
}

View File

@ -1,45 +0,0 @@
package main
import (
"fmt"
"git.kill0.net/chill9/go-lifx"
"os"
//"time"
)
func main() {
accessToken := os.Getenv("LIFX_ACCESS_TOKEN")
if accessToken == "" {
fmt.Println("LIFX_ACCESS_TOKEN is undefined")
os.Exit(1)
}
color1 := lifx.RGBColor{R: 235, G: 191, B: 255}
color2 := lifx.NewHSBKColor()
color2.H = 27
color2.S = 1
color2.B = 0.39
fmt.Println(color1.Hex())
fmt.Println(color1.ColorString())
fmt.Println(color2.ColorString())
s := lifx.State{Power: "on", Color: color2}
c := lifx.NewClient(accessToken)
selector := "group:Office"
r, err := c.FastSetState(selector, s)
/*
time.Sleep(10 * time.Second)
s.Color = "white"
res, _ := c.SetState(selector, s)
fmt.Println(res)
//c.SetState("all", &lifx.State{Power: "on", Color: "green"})
time.Sleep(10 * time.Second)
c.FastPowerOff(selector)
time.Sleep(10 * time.Second)
c.FastPowerOn(selector)
//c.PowerOff("all")
*/
fmt.Println(err)
fmt.Println(r)
r, err = c.Toggle(selector, 10.0)
fmt.Println(err)
fmt.Println(r)
}

48
cmd/ls.go Normal file
View File

@ -0,0 +1,48 @@
package lumecmd
import (
"flag"
)
func NewCmdLs() Command {
return Command{
Name: "ls",
Func: LsCmd,
Flags: func() *flag.FlagSet {
fs := flag.NewFlagSet("ls", flag.ExitOnError)
selector := fs.String("selector", defaultSelector, "Set the selector")
fs.StringVar(selector, "s", defaultSelector, "Set the selector")
fs.String("format", defaultOutputFormat, "Set the output format")
return fs
}(),
Use: "[--selector=<selector>]",
Short: "List the lights",
}
}
func LsCmd(args CmdArgs) (int, error) {
c := args.Client
selector := args.Flags.String("selector")
format := args.Flags.String("format")
if format == "" && args.Config.OutputFormat != "" {
format = args.Config.OutputFormat
}
lights, err := c.ListLights(selector)
if err != nil {
return ExitFailure, err
}
switch format {
case "table":
PrintLightsTable(lights)
default:
PrintLights(lights)
}
return ExitSuccess, nil
}

19
cmd/lume/init_windows.go Normal file
View File

@ -0,0 +1,19 @@
// +build windows
// https://stackoverflow.com/a/52579002
package main
import (
"os"
"golang.org/x/sys/windows"
)
func init() {
stdout := windows.Handle(os.Stdout.Fd())
var originalMode uint32
windows.GetConsoleMode(stdout, &originalMode)
windows.SetConsoleMode(stdout, originalMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING)
}

11
cmd/lume/main.go Normal file
View File

@ -0,0 +1,11 @@
package main
import (
"os"
lumecmd "git.kill0.net/chill9/lume/cmd"
)
func main() {
lumecmd.ExitWithCode(lumecmd.Main(os.Args))
}

133
cmd/main.go Normal file
View File

@ -0,0 +1,133 @@
package lumecmd
import (
"errors"
"flag"
"fmt"
"os"
"path"
"strings"
"git.kill0.net/chill9/lifx-go"
"github.com/BurntSushi/toml"
)
var userAgent string
func init() {
userAgent = initUserAgent()
RegisterCommand(NewCmdHelp())
RegisterCommand(NewCmdLs())
RegisterCommand(NewCmdPoweroff())
RegisterCommand(NewCmdPoweron())
RegisterCommand(NewCmdSetColor())
RegisterCommand(NewCmdSetState())
RegisterCommand(NewCmdSetWhite())
RegisterCommand(NewCmdShow())
RegisterCommand(NewCmdToggle())
RegisterCommand(NewCmdVersion())
}
var Version string
var BuildDate string
var GitCommit string
const lumercFile string = ".lumerc"
func Main(args []string) (int, error) {
var config Config
var err error
if len(args) == 1 {
args = append(args, "help")
}
configPath := getConfigPath()
if configPath == "" {
err = errors.New("fatal: ~/.lumerc was not found")
return ExitFailure, err
}
if _, err := toml.DecodeFile(configPath, &config); err != nil {
err = fmt.Errorf("fatal: failed to parse %s; %w", configPath, err)
return ExitFailure, err
}
envAccessToken := os.Getenv("LIFX_ACCESS_TOKEN")
if envAccessToken != "" {
config.AccessToken = envAccessToken
}
if err = config.Validate(); err != nil {
return ExitFailure, fmt.Errorf("fatal: %s", err)
}
flag.Parse()
command := args[1]
c := lifx.NewClient(
config.AccessToken,
lifx.WithUserAgent(userAgent),
)
cmdArgs := CmdArgs{
Client: c,
Config: config,
Args: args[2:],
}
cmd, ok := GetCommand(command)
if !ok {
err = fmt.Errorf("lume: '%s' is not lume command. See 'lume help'", command)
return ExitFailure, err
}
fs := cmd.Flags
if fs != nil {
fs.Parse(args[2:])
cmdArgs.Flags = Flags{FlagSet: fs}
}
cmdArgs.Name = command
exitCode, err := cmd.Func(cmdArgs)
if err != nil {
err = fmt.Errorf("fatal: %s", err)
}
return exitCode, err
}
func getConfigPath() string {
var tryPath, configPath string
// ~/.lumerc
homeDir, err := os.UserHomeDir()
if err == nil {
tryPath = path.Join(homeDir, lumercFile)
if _, err := os.Stat(tryPath); !os.IsNotExist(err) {
configPath = tryPath
}
}
// ./.lumerc
cwd, err := os.Getwd()
if err == nil {
tryPath = path.Join(cwd, lumercFile)
if _, err := os.Stat(tryPath); !os.IsNotExist(err) {
configPath = tryPath
}
}
return configPath
}
func initUserAgent() string {
var b strings.Builder
b.WriteString("lume")
b.WriteRune('/')
b.WriteString(Version)
return b.String()
}

55
cmd/poweroff.go Normal file
View File

@ -0,0 +1,55 @@
package lumecmd
import (
"flag"
"git.kill0.net/chill9/lifx-go"
)
func NewCmdPoweroff() Command {
return Command{
Name: "poweroff",
Func: PoweroffCmd,
Flags: func() *flag.FlagSet {
fs := flag.NewFlagSet("poweroff", flag.ExitOnError)
duration := fs.Float64("duration", defaultDuration, "Set the duration")
fs.Float64Var(duration, "d", defaultDuration, "Set the duration")
selector := fs.String("selector", defaultSelector, "Set the selector")
fs.StringVar(selector, "s", defaultSelector, "Set the selector")
fs.String("format", defaultOutputFormat, "Set the output format")
return fs
}(),
Use: "[--selector <selector>] [--duration <sec>]",
Short: "Power on",
}
}
func PoweroffCmd(args CmdArgs) (int, error) {
c := args.Client
duration := args.Flags.Float64("duration")
selector := args.Flags.String("selector")
format := args.Flags.String("format")
state := lifx.State{Power: "off", Duration: duration}
if format == "" && args.Config.OutputFormat != "" {
format = args.Config.OutputFormat
}
r, err := c.SetState(selector, state)
if err != nil {
return ExitFailure, err
}
switch format {
case "table":
PrintResultsTable(r.Results)
default:
PrintResults(r.Results)
}
return ExitSuccess, nil
}

55
cmd/poweron.go Normal file
View File

@ -0,0 +1,55 @@
package lumecmd
import (
"flag"
"git.kill0.net/chill9/lifx-go"
)
func NewCmdPoweron() Command {
return Command{
Name: "poweron",
Func: PoweronCmd,
Flags: func() *flag.FlagSet {
fs := flag.NewFlagSet("poweron", flag.ExitOnError)
duration := fs.Float64("duration", defaultDuration, "Set the duration")
fs.Float64Var(duration, "d", defaultDuration, "Set the duration")
selector := fs.String("selector", defaultSelector, "Set the selector")
fs.StringVar(selector, "s", defaultSelector, "Set the selector")
fs.String("format", defaultOutputFormat, "Set the output format")
return fs
}(),
Use: "[--selector <selector>] [--duration <sec>]",
Short: "Power on",
}
}
func PoweronCmd(args CmdArgs) (int, error) {
c := args.Client
duration := args.Flags.Float64("duration")
selector := args.Flags.String("selector")
format := args.Flags.String("format")
state := lifx.State{Power: "on", Duration: duration}
if format == "" && args.Config.OutputFormat != "" {
format = args.Config.OutputFormat
}
r, err := c.SetState(selector, state)
if err != nil {
return ExitFailure, err
}
switch format {
case "table":
PrintResultsTable(r.Results)
default:
PrintResults(r.Results)
}
return ExitSuccess, nil
}

145
cmd/print.go Normal file
View File

@ -0,0 +1,145 @@
package lumecmd
import (
"fmt"
"os"
"time"
"git.kill0.net/chill9/lifx-go"
"github.com/fatih/color"
"github.com/olekukonko/tablewriter"
)
func ColorizePower(s string) string {
c := color.New(color.FgRed)
if s == "on" {
c = color.New(color.FgGreen)
}
return c.Sprint(s)
}
func ColorizeStatus(s lifx.Status) string {
c := color.New(color.FgRed)
if s == "ok" {
c = color.New(color.FgGreen)
}
return c.Sprint(s)
}
func PrintWithIndent(indent int, s string) {
fmt.Printf("%*s%s", indent, "", s)
}
func PrintfWithIndent(indent int, format string, a ...interface{}) (n int, err error) {
format = fmt.Sprintf("%*s%s", indent, "", format)
return fmt.Printf(format, a...)
}
func makeLightsTable(lights []lifx.Light) (hdr []string, rows [][]string) {
hdr = []string{"ID", "Location", "Group", "Label", "Last Seen", "Power"}
for _, l := range lights {
rows = append(rows, []string{
fmt.Sprint(l.Id),
fmt.Sprint(l.Location.Name),
fmt.Sprint(l.Group.Name),
fmt.Sprint(l.Label),
fmt.Sprint(l.LastSeen.Local().Format(time.RFC3339)),
fmt.Sprint(ColorizePower(l.Power)),
})
}
return
}
func makeResultsTable(results []lifx.Result) (hdr []string, rows [][]string) {
hdr = []string{"ID", "Label", "Status"}
for _, r := range results {
rows = append(rows, []string{
fmt.Sprint(r.Id),
fmt.Sprint(r.Label),
fmt.Sprint(ColorizeStatus(r.Status)),
})
}
return
}
func PrintLights(lights []lifx.Light) {
sortLights(lights)
table := tablewriter.NewWriter(os.Stdout)
_, rows := makeLightsTable(lights)
for _, v := range rows {
table.Append(v)
}
fmt.Printf("total %d\n", len(lights))
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetAutoWrapText(false)
table.SetBorder(false)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetHeaderLine(false)
table.SetNoWhiteSpace(true)
table.SetRowSeparator("")
table.SetTablePadding(" ")
table.Render()
}
func PrintLightsTable(lights []lifx.Light) {
sortLights(lights)
table := tablewriter.NewWriter(os.Stdout)
hdr, rows := makeLightsTable(lights)
for _, v := range rows {
table.Append(v)
}
table.SetHeader(hdr)
table.Render()
}
func PrintResults(results []lifx.Result) {
sortResults(results)
table := tablewriter.NewWriter(os.Stdout)
_, rows := makeResultsTable(results)
for _, v := range rows {
table.Append(v)
}
fmt.Printf("total %d\n", len(results))
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetAutoWrapText(false)
table.SetBorder(false)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetHeaderLine(false)
table.SetNoWhiteSpace(true)
table.SetRowSeparator("")
table.SetTablePadding(" ")
table.Render()
}
func PrintResultsTable(results []lifx.Result) {
sortResults(results)
table := tablewriter.NewWriter(os.Stdout)
hdr, rows := makeResultsTable(results)
for _, v := range rows {
table.Append(v)
}
table.SetHeader(hdr)
table.Render()
}

138
cmd/setcolor.go Normal file
View File

@ -0,0 +1,138 @@
package lumecmd
import (
"flag"
"fmt"
"git.kill0.net/chill9/lifx-go"
)
func NewCmdSetColor() Command {
return Command{
Name: "set-color",
Func: SetColorCmd,
Flags: func() *flag.FlagSet {
fs := flag.NewFlagSet("set-color", flag.ExitOnError)
selector := fs.String("selector", "all", "the selector")
fs.StringVar(selector, "s", "all", "the selector")
power := fs.String("power", defaultPower, "power state")
fs.StringVar(power, "p", defaultPower, "power state")
hue := fs.String("hue", defaultHue, "hue level")
fs.StringVar(hue, "H", defaultHue, "hue level")
saturation := fs.String("saturation", defaultSaturation, "saturation level")
fs.StringVar(saturation, "S", defaultSaturation, "saturation level")
rgb := fs.String("rgb", defaultRGB, "RGB value")
fs.StringVar(rgb, "r", defaultRGB, "RGB value")
name := fs.String("name", defaultName, "named color")
fs.StringVar(name, "n", defaultName, "named color")
brightness := fs.String("brightness", defaultBrightness, "brightness state")
fs.StringVar(brightness, "b", defaultBrightness, "brightness state")
duration := fs.Float64("duration", defaultDuration, "duration state")
fs.Float64Var(duration, "d", defaultDuration, "duration state")
fast := fs.Bool("fast", defaultFast, "fast state")
fs.BoolVar(fast, "f", defaultFast, "fast state")
fs.String("format", defaultOutputFormat, "Set the output format")
return fs
}(),
Use: "[--selector <selector>] [--power (on|off)] [--hue <hue>] [--saturation <saturation>] [--rgb <rbg>] [--name <color>] [--brightness <brightness>] [--duration <sec>] [--fast]",
Short: "Set the color",
}
}
func SetColorCmd(args CmdArgs) (int, error) {
c := args.Client
state := lifx.State{}
selector := args.Flags.String("selector")
format := args.Flags.String("format")
if format == "" && args.Config.OutputFormat != "" {
format = args.Config.OutputFormat
}
power := args.Flags.String("power")
if power != "" {
state.Power = power
}
hueFlag := args.Flags.String("hue")
saturationFlag := args.Flags.String("saturation")
rgbFlag := args.Flags.String("rgb")
name := args.Flags.String("name")
if (hueFlag == "" || saturationFlag == "") && rgbFlag == "" && name == "" {
printCmdHelp(args.Name)
return ExitFailure, nil
}
if hueFlag != "" || saturationFlag != "" {
color := lifx.HSBKColor{}
if hueFlag != "" {
hue := args.Flags.Float32("hue")
color.H = lifx.Float32Ptr(hue)
}
if saturationFlag != "" {
saturation := args.Flags.Float32("saturation")
color.S = lifx.Float32Ptr(saturation)
}
state.Color = color
} else if rgbFlag != "" {
color, err := parseRGB(rgbFlag)
if err != nil {
return ExitFailure, err
}
state.Color = color
} else if name != "" {
hsb, ok := args.Config.Colors[name]
if !ok {
return ExitFailure, fmt.Errorf("%s is not a defined color", name)
}
color, err := lifx.NewHSBColor(hsb[0], hsb[1], hsb[2])
if err != nil {
return ExitFailure, err
}
state.Color = color
}
brightnessFlag := args.Flags.String("brightness")
if brightnessFlag != "" {
brightness := args.Flags.Float64("brightness")
state.Brightness = brightness
}
duration := args.Flags.Float64("duration")
state.Duration = duration
fast := args.Flags.Bool("fast")
state.Fast = fast
r, err := c.SetState(selector, state)
if err != nil {
fmt.Printf("fatal: %s\n", err)
return ExitFailure, err
}
if !fast {
switch format {
case "table":
PrintResultsTable(r.Results)
default:
PrintResults(r.Results)
}
}
return ExitSuccess, nil
}

104
cmd/setstate.go Normal file
View File

@ -0,0 +1,104 @@
package lumecmd
import (
"flag"
"git.kill0.net/chill9/lifx-go"
)
func NewCmdSetState() Command {
return Command{
Name: "set-state",
Func: SetStateCmd,
Flags: func() *flag.FlagSet {
fs := flag.NewFlagSet("set-state", flag.ExitOnError)
selector := fs.String("selector", defaultSelector, "Set the selector")
fs.StringVar(selector, "s", defaultSelector, "Set the selector")
power := fs.String("power", defaultPower, "power state")
fs.StringVar(power, "p", defaultPower, "power state")
color := fs.String("color", defaultColor, "color state")
fs.StringVar(color, "c", defaultColor, "color state")
brightness := fs.String("brightness", defaultBrightness, "brightness state")
fs.StringVar(brightness, "b", defaultBrightness, "brightness state")
duration := fs.Float64("duration", defaultDuration, "duration state")
fs.Float64Var(duration, "d", defaultDuration, "duration state")
infrared := fs.String("infrared", defaultInfrared, "infrared state")
fs.StringVar(infrared, "i", defaultInfrared, "infrared state")
fast := fs.Bool("fast", defaultFast, "fast state")
fs.BoolVar(fast, "f", defaultFast, "fast state")
fs.String("format", defaultOutputFormat, "Set the output format")
return fs
}(),
Use: "[--selector <selector>] [--power (on|off)] [--color <color>] [--brightness <brightness>] [--duration <sec>] [--infrared <infrared>] [--fast]",
Short: "Set various state attributes",
}
}
func SetStateCmd(args CmdArgs) (int, error) {
c := args.Client
state := lifx.State{}
selector := args.Flags.String("selector")
format := args.Flags.String("format")
if format == "" && args.Config.OutputFormat != "" {
format = args.Config.OutputFormat
}
power := args.Flags.String("power")
if power != "" {
state.Power = power
}
color := args.Flags.String("color")
if color != "" {
state.Color = lifx.NamedColor(color)
}
brightnessFlag := args.Flags.String("brightness")
if brightnessFlag != "" {
brightness := args.Flags.Float64("brightness")
state.Brightness = brightness
}
duration := args.Flags.Float64("duration")
state.Duration = duration
infraredFlag := args.Flags.String("infrared")
if infraredFlag != "" {
infrared := args.Flags.Float64("infrared")
state.Infrared = infrared
}
fast := args.Flags.Bool("fast")
state.Fast = fast
if power == "" && color == "" && brightnessFlag == "" && infraredFlag == "" {
printCmdHelp(args.Name)
return ExitFailure, nil
}
r, err := c.SetState(selector, state)
if err != nil {
return ExitFailure, err
}
if !fast {
switch format {
case "table":
PrintResultsTable(r.Results)
default:
PrintResults(r.Results)
}
}
return ExitSuccess, nil
}

122
cmd/setwhite.go Normal file
View File

@ -0,0 +1,122 @@
package lumecmd
import (
"flag"
"git.kill0.net/chill9/lifx-go"
)
func NewCmdSetWhite() Command {
return Command{
Name: "set-white",
Func: SetWhiteCmd,
Flags: func() *flag.FlagSet {
fs := flag.NewFlagSet("set-white", flag.ExitOnError)
selector := fs.String("selector", "all", "the selector")
fs.StringVar(selector, "s", "all", "the selector")
power := fs.String("power", defaultPower, "power state")
fs.StringVar(power, "p", defaultPower, "power state")
kelvin := fs.String("kelvin", defaultWhiteKelvin, "kelvin level")
fs.StringVar(kelvin, "k", defaultWhiteKelvin, "kelvin level")
name := fs.String("name", defaultWhiteName, "named white level")
fs.StringVar(name, "n", defaultWhiteName, "named white level")
brightness := fs.String("brightness", defaultBrightness, "brightness state")
fs.StringVar(brightness, "b", defaultBrightness, "brightness state")
duration := fs.Float64("duration", defaultDuration, "duration state")
fs.Float64Var(duration, "d", defaultDuration, "duration state")
infrared := fs.String("infrared", defaultInfrared, "infrared state")
fs.StringVar(infrared, "i", defaultInfrared, "infrared state")
fast := fs.Bool("fast", defaultFast, "fast state")
fs.BoolVar(fast, "f", defaultFast, "fast state")
fs.String("format", defaultOutputFormat, "Set the output format")
return fs
}(),
Use: "[--selector <selector>] [--power (on|off)] [--kelvin <kelvin>] [--name <color>] [--brightness <brightness>] [--duration <sec>] [--infrared] [--fast]",
Short: "Set the white level",
}
}
func SetWhiteCmd(args CmdArgs) (int, error) {
c := args.Client
state := lifx.State{}
selector := args.Flags.String("selector")
format := args.Flags.String("format")
if format == "" && args.Config.OutputFormat != "" {
format = args.Config.OutputFormat
}
power := args.Flags.String("power")
if power != "" {
state.Power = power
}
kelvinFlag := args.Flags.String("kelvin")
if kelvinFlag != "" {
kelvin := args.Flags.Int16("kelvin")
color, err := lifx.NewWhite(kelvin)
if err != nil {
return ExitFailure, err
}
state.Color = color
}
name := args.Flags.String("name")
if name != "" {
name := args.Flags.String("name")
color, err := lifx.NewWhiteString(name)
if err != nil {
return ExitFailure, err
}
state.Color = color
}
brightnessFlag := args.Flags.String("brightness")
if brightnessFlag != "" {
brightness := args.Flags.Float64("brightness")
state.Brightness = brightness
}
duration := args.Flags.Float64("duration")
state.Duration = duration
infraredFlag := args.Flags.String("infrared")
if infraredFlag != "" {
infrared := args.Flags.Float64("infrared")
state.Infrared = infrared
}
fast := args.Flags.Bool("fast")
state.Fast = fast
if power == "" && kelvinFlag == "" && name == "" && brightnessFlag == "" && infraredFlag == "" {
printCmdHelp(args.Name)
return ExitFailure, nil
}
r, err := c.SetState(selector, state)
if err != nil {
return ExitFailure, err
}
if !fast {
switch format {
case "table":
PrintResultsTable(r.Results)
default:
PrintResults(r.Results)
}
}
return ExitSuccess, nil
}

92
cmd/show.go Normal file
View File

@ -0,0 +1,92 @@
package lumecmd
import (
"flag"
"fmt"
)
const Tabstop int = 2
func NewCmdShow() Command {
return Command{
Name: "show",
Func: ShowCmd,
Flags: func() *flag.FlagSet {
fs := flag.NewFlagSet("show", flag.ExitOnError)
selector := fs.String("selector", defaultSelector, "Set the selector")
fs.StringVar(selector, "s", defaultSelector, "Set the selector")
return fs
}(),
Use: "[--selector=<selector>]",
Short: "Show details about the lights",
}
}
func ShowCmd(args CmdArgs) (int, error) {
var indent int
c := args.Client
selector := args.Flags.String("selector")
lights, err := c.ListLights(selector)
if err != nil {
return ExitFailure, err
}
sortLights(lights)
for i, l := range lights {
indent = 0
fmt.Printf(
"Light ID: %s, %s, Power: %s\n",
l.Id,
connected(l.Connected),
ColorizePower(l.Power),
)
indent += Tabstop
PrintfWithIndent(indent, "Label: %s, ID: %s\n", l.Label, l.Id)
PrintfWithIndent(indent, "UUID: %s\n", l.UUID)
PrintfWithIndent(indent, "Location: %s, ID: %s\n", l.Location.Name, l.Location.Id)
PrintfWithIndent(indent, "Group: %s, ID: %s\n", l.Group.Name, l.Group.Id)
PrintfWithIndent(indent, "Color: Hue: %.1f, Saturation: %.1f%%, Kelvin: %d\n",
*l.Color.H, *l.Color.S, *l.Color.K)
PrintfWithIndent(indent, "Brightness: %.1f%%\n", l.Brightness*100)
if l.Effect != "" {
PrintfWithIndent(indent, "Effect: %s\n", l.Effect)
}
PrintfWithIndent(indent, "Product: %s\n", l.Product.Name)
PrintfWithIndent(indent, "Capabilities: ")
fmt.Printf("Color: %s, ", YesNo(l.Product.Capabilities.HasColor))
fmt.Printf("Variable Color Temp: %s, ", YesNo(l.Product.Capabilities.HasVariableColorTemp))
fmt.Printf("IR: %s, ", YesNo(l.Product.Capabilities.HasIR))
fmt.Printf("Chain: %s, ", YesNo(l.Product.Capabilities.HasChain))
fmt.Printf("Multizone: %s, ", YesNo(l.Product.Capabilities.HasMultizone))
fmt.Printf("Min Kelvin: %.1f, ", l.Product.Capabilities.MinKelvin)
fmt.Printf("Max Kelvin: %.1f ", l.Product.Capabilities.MaxKelvin)
fmt.Println()
// List applicable selectors (most to least specific)
PrintfWithIndent(indent, "Selectors:\n")
indent += Tabstop
PrintfWithIndent(indent, "id:%s\n", l.Id)
PrintfWithIndent(indent, "label:%s\n", l.Label)
PrintfWithIndent(indent, "group_id:%s\n", l.Group.Id)
PrintfWithIndent(indent, "group:%s\n", l.Group.Name)
PrintfWithIndent(indent, "location_id:%s\n", l.Location.Id)
PrintfWithIndent(indent, "location:%s\n", l.Location.Name)
indent -= Tabstop
PrintfWithIndent(indent, "Last Seen: %s (%.1fs ago)\n", l.LastSeen, l.SecondsLastSeen)
if i < len(lights)-1 {
fmt.Println()
}
}
return ExitSuccess, nil
}
func connected(c bool) string {
if c {
return "Connected"
}
return "Disconnected"
}

52
cmd/toggle.go Normal file
View File

@ -0,0 +1,52 @@
package lumecmd
import (
"flag"
)
func NewCmdToggle() Command {
return Command{
Name: "toggle",
Func: ToggleCmd,
Flags: func() *flag.FlagSet {
fs := flag.NewFlagSet("toggle", flag.ExitOnError)
duration := fs.Float64("duration", defaultDuration, "Set the duration")
fs.Float64Var(duration, "d", defaultDuration, "Set the duration")
selector := fs.String("selector", defaultSelector, "Set the selector")
fs.StringVar(selector, "s", defaultSelector, "Set the selector")
fs.String("format", defaultOutputFormat, "Set the output format")
return fs
}(),
Use: "[--selector <selector>] [--duration <sec>]",
Short: "Toggle the power on/off",
}
}
func ToggleCmd(args CmdArgs) (int, error) {
c := args.Client
duration := args.Flags.Float64("duration")
selector := args.Flags.String("selector")
format := args.Flags.String("format")
if format == "" && args.Config.OutputFormat != "" {
format = args.Config.OutputFormat
}
r, err := c.Toggle(selector, duration)
if err != nil {
return ExitFailure, err
}
switch format {
case "table":
PrintResultsTable(r.Results)
default:
PrintResults(r.Results)
}
return ExitSuccess, nil
}

62
cmd/util.go Normal file
View File

@ -0,0 +1,62 @@
package lumecmd
import (
"fmt"
"os"
"sort"
"strconv"
"strings"
"git.kill0.net/chill9/lifx-go"
)
func parseRGB(s string) (lifx.RGBColor, error) {
var c lifx.RGBColor
rgb := strings.SplitN(s, ",", 3)
r, err := strconv.ParseUint(rgb[0], 10, 8)
if err != nil {
return c, err
}
g, err := strconv.ParseUint(rgb[1], 10, 8)
if err != nil {
return c, err
}
b, err := strconv.ParseUint(rgb[2], 10, 8)
if err != nil {
return c, err
}
return lifx.NewRGBColor(uint8(r), uint8(g), uint8(b))
}
func sortLights(lights []lifx.Light) {
sort.Slice(lights, func(i, j int) bool {
if lights[i].Group.Name < lights[j].Group.Name {
return true
}
if lights[i].Group.Name > lights[j].Group.Name {
return false
}
return lights[i].Label < lights[j].Label
})
}
func sortResults(res []lifx.Result) {
sort.Slice(res, func(i, j int) bool {
return res[i].Label < res[j].Label
})
}
func ExitWithCode(code int, err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
}
os.Exit(code)
}
func YesNo(v bool) string {
if v {
return "yes"
}
return "no"
}

33
cmd/version.go Normal file
View File

@ -0,0 +1,33 @@
package lumecmd
import (
"fmt"
"strings"
)
func NewCmdVersion() Command {
return Command{
Name: "version",
Func: VersionCmd,
Flags: nil,
Use: "",
Short: "Show version",
}
}
func VersionCmd(args CmdArgs) (int, error) {
var b strings.Builder
fmt.Fprintf(&b, "lume %s", Version)
b.WriteString(" ")
if GitCommit != "" {
fmt.Fprintf(&b, "(git: %s)", GitCommit)
b.WriteString(" ")
}
if BuildDate != "" {
fmt.Fprintf(&b, "build_date: %s", BuildDate)
}
fmt.Println(b.String())
return ExitSuccess, nil
}

View File

@ -1,85 +0,0 @@
package lifx
import (
"fmt"
"strings"
)
type (
Color interface {
ColorString() string
}
)
type (
RGBColor struct {
R, G, B uint8
}
HSBKColor struct {
H float32 `json:"hue,omitempty"`
S float32 `json:"saturation,omitempty"`
B float32 `json:"brightness,omitempty"`
K int16 `json:"kelvin,omitempty"`
}
NamedColor string
)
func NewRGBColor(r, g, b uint8) (*RGBColor, error) {
return &RGBColor{R: r, G: g, B: b}, nil
}
func NewHSBKColor() HSBKColor {
var c HSBKColor
c.H, c.S, c.B, c.K = -1, -1, -1, -1
return c
}
func (c RGBColor) ColorString() string {
return fmt.Sprintf("rgb:%d,%d,%d", c.R, c.G, c.B)
}
func (c RGBColor) Hex() string {
return fmt.Sprintf("#%x%x%x", c.R, c.G, c.B)
}
func (c HSBKColor) ColorString() string {
var s []string
if c.H >= 0 {
s = append(s, fmt.Sprintf("hue:%f", c.H))
}
if c.S >= 0 {
s = append(s, fmt.Sprintf("saturation:%g", c.S))
}
if c.B >= 0 {
s = append(s, fmt.Sprintf("brightness:%g", c.B))
}
if c.K >= 0 {
s = append(s, fmt.Sprintf("kelvin:%d", c.K))
}
return strings.Join(s, " ")
}
func (c HSBKColor) MarshalText() ([]byte, error) {
return []byte(c.ColorString()), nil
}
func (c NamedColor) ColorString() string {
return string(c)
}
func (c *Client) ValidateColor(color Color) (Color, error) {
resp, err := c.Request("GET", EndpointColor(color.ColorString()), nil)
if err != nil {
return nil, err
}
s := &HSBKColor{}
err = c.UnmarshalResponse(resp, s)
if err != nil {
return nil, err
}
return s, nil
}

View File

@ -1,33 +0,0 @@
package lifx
import (
"fmt"
"net/url"
"path"
)
func BuildURL(rawurl, rawpath string) string {
u, _ := url.Parse(rawurl)
u.Path = path.Join(u.Path, rawpath)
return u.String()
}
var (
Endpoint = "https://api.lifx.com/v1"
EndpointState = func(selector string) string {
return BuildURL(Endpoint, fmt.Sprintf("/lights/%s/state", selector))
}
EndpointStates = func() string {
return BuildURL(Endpoint, "/lights/states")
}
EndpointColor = func(color string) string {
u, _ := url.Parse(BuildURL(Endpoint, "/color"))
q := u.Query()
q.Set("string", color)
u.RawQuery = q.Encode()
return u.String()
}
EndpointToggle = func(selector string) string {
return BuildURL(Endpoint, fmt.Sprintf("/lights/%s/toggle", selector))
}
)

11
go.mod Normal file
View File

@ -0,0 +1,11 @@
module git.kill0.net/chill9/lume
go 1.15
require (
git.kill0.net/chill9/lifx-go v0.0.0-20210215004437-f86c28b0a5ef
github.com/BurntSushi/toml v0.3.1
github.com/fatih/color v1.10.0
github.com/olekukonko/tablewriter v0.0.5
golang.org/x/sys v0.0.0-20210110051926-789bb1bd4061
)

18
go.sum Normal file
View File

@ -0,0 +1,18 @@
git.kill0.net/chill9/lifx-go v0.0.0-20210215004437-f86c28b0a5ef h1:8yyXAk+qiRvrowTeHHAOBZqGXXCr8SxWFydez61ZGp8=
git.kill0.net/chill9/lifx-go v0.0.0-20210215004437-f86c28b0a5ef/go.mod h1:ZFKIcwdJ4Nqlrkn/eUHbeLt0NVhFsfxBREkVoA+jzUc=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/fatih/color v1.10.0 h1:s36xzo75JdqLaaWoiEHk767eHiwo0598uUxyfiPkDsg=
github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM=
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210110051926-789bb1bd4061 h1:DQmQoKxQWtyybCtX/3dIuDBcAhFszqq8YiNeS6sNu1c=
golang.org/x/sys v0.0.0-20210110051926-789bb1bd4061/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=

129
lights.go
View File

@ -1,129 +0,0 @@
package lifx
import (
"bytes"
//"crypto/tls"
"encoding/json"
)
const (
OK Status = "ok"
TimedOut Status = "timed_out"
Offline Status = "offline"
)
type (
Status string
State struct {
Power string `json:"power,omitempty"`
Color Color `json:"color,omitempty"`
Brightness float64 `json:"brightness,omitempty"`
Duration float64 `json:"duration,omitempty"`
Infrared float64 `json:"infrared,omitempty"`
Fast bool `json:"fast,omitempty"`
}
StateWithSelector struct {
State
Selector string `json:"selector"`
}
States struct {
States []StateWithSelector `json:"states",omitempty`
Defaults State `json:"defaults",omitempty`
}
Toggle struct {
Duration float64 `json:"duration,omitempty"`
}
)
func (s Status) Success() bool {
return s == OK
}
func (c *Client) SetState(selector string, state State) ([]Result, error) {
j, err := json.Marshal(state)
if err != nil {
return nil, err
}
resp, err := c.Request("PUT", EndpointState(selector), bytes.NewBuffer(j))
if err != nil {
return nil, err
}
if state.Fast {
return nil, nil
}
s := &Results{}
err = c.UnmarshalResponse(resp, s)
if err != nil {
return nil, err
}
return s.Results, nil
}
func (c *Client) FastSetState(selector string, state State) ([]Result, error) {
state.Fast = true
return c.SetState(selector, state)
}
func (c *Client) SetStates(states States) ([]Result, error) {
j, err := json.Marshal(states)
if err != nil {
return nil, err
}
resp, err := c.Request("PUT", EndpointStates(), bytes.NewBuffer(j))
if err != nil {
return nil, err
}
s := &Results{}
err = c.UnmarshalResponse(resp, s)
if err != nil {
return nil, err
}
return s.Results, nil
}
func (c *Client) Toggle(selector string, duration float64) ([]Result, error) {
j, err := json.Marshal(&Toggle{Duration: duration})
if err != nil {
return nil, err
}
resp, err := c.Request("POST", EndpointToggle(selector), bytes.NewBuffer(j))
if err != nil {
return nil, err
}
s := &Results{}
err = c.UnmarshalResponse(resp, s)
if err != nil {
return nil, err
}
return s.Results, nil
}
func (c *Client) PowerOff(selector string) ([]Result, error) {
return c.SetState(selector, State{Power: "off"})
}
func (c *Client) FastPowerOff(selector string) {
c.SetState(selector, State{Power: "off", Fast: true})
}
func (c *Client) PowerOn(selector string) ([]Result, error) {
return c.SetState(selector, State{Power: "on"})
}
func (c *Client) FastPowerOn(selector string) {
c.SetState(selector, State{Power: "on", Fast: true})
}