tuya_iot_lights 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ce9c4bca9a0e120af36c1c2aeeeb003abc88d8466be861bdcaa97a4638c962d2
4
+ data.tar.gz: 4f36e6a4252bc3cabb0ab621edf9fda75d447332d43651a58197b9902172e54f
5
+ SHA512:
6
+ metadata.gz: 04bda534fa1add5b96e39496418ad7d7c197dcd3a3a827c1a39a446c5de90c633d2c7634ffbf4b2f1e846c67cf9712323752cf9da876995f5f20dd1b30b9fe1a
7
+ data.tar.gz: 3fa8141b2d4d7da5f63fff9f519844fd5b41e232667578d1577e0ffb1a0f49bc77b232a6843cd0e7c19c182e82b8c8629089005c34e63eefa46643148cbd85a2
data/.standard.yml ADDED
@@ -0,0 +1,3 @@
1
+ # For available configuration options, see:
2
+ # https://github.com/standardrb/standard
3
+ ruby_version: 3.0
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-07-28
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Matt Hinczuk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,242 @@
1
+ # TuyaIotLights
2
+
3
+ A Ruby gem for controlling Tuya IoT smart lights with easy color changes and white mode switching through the Tuya Cloud API.
4
+
5
+ ## Features
6
+
7
+ - 🎨 Control smart light colors with simple commands
8
+ - 🤍 Switch to white mode easily
9
+ - 🌈 Pre-defined color palette with 12 colors
10
+ - 🔐 Secure credential management with encrypted storage
11
+ - 💎 Clean Ruby API for programmatic use
12
+ - 🚀 Command-line interface for quick usage
13
+ - ✅ Input validation and error handling
14
+ - 🔒 SSL certificate verification and request timeouts
15
+
16
+ ## Installation
17
+
18
+ Install the gem:
19
+
20
+ ```bash
21
+ gem install tuya_iot_lights
22
+ ```
23
+
24
+ Or add to your Gemfile:
25
+
26
+ ```ruby
27
+ gem 'tuya_iot_lights'
28
+ ```
29
+
30
+ ## Quick Start
31
+
32
+ ### 1. Get Tuya Cloud API Credentials
33
+
34
+ 1. Sign up at [Tuya IoT Platform](https://iot.tuya.com/)
35
+ 2. Create a cloud project
36
+ 3. Get your `Client ID`, `Client Secret`, and `Device ID`
37
+
38
+ ### 2. Configure Your Credentials (CLI Only)
39
+
40
+ ```bash
41
+ tuya_light configure
42
+ ```
43
+
44
+ This will prompt you to enter your credentials securely. **Note: Credentials are only stored for CLI usage** and are saved in `~/.tuya_iot_lights/config.yml` with proper file permissions (600 - owner read/write only).
45
+
46
+ **For programmatic usage**, credentials are passed directly to the constructor and are never stored to disk.
47
+
48
+ ### 3. Control Your Lights
49
+
50
+ ```bash
51
+ # Change light to blue
52
+ tuya_light blue
53
+
54
+ # Switch to white mode
55
+ tuya_light normal
56
+
57
+ # List available colors
58
+ tuya_light --colors
59
+
60
+ # Show help
61
+ tuya_light --help
62
+ ```
63
+
64
+ ## Usage
65
+
66
+ ### Command Line Interface
67
+
68
+ The CLI provides a simple interface for controlling your lights:
69
+
70
+ ```bash
71
+ tuya_light configure # Set up your API credentials (run once)
72
+ tuya_light red # Change light to red
73
+ tuya_light blue # Change light to blue
74
+ tuya_light normal # Switch to white mode
75
+ tuya_light --colors # List all available colors
76
+ tuya_light --help # Show help
77
+ ```
78
+
79
+ ### Available Colors
80
+
81
+ - red, orange, yellow, green, cyan, blue, purple, magenta
82
+ - pink, white, warm_white, cool_white
83
+ - normal (switches to white mode)
84
+
85
+ ### Ruby API
86
+
87
+ ```ruby
88
+ require 'tuya_iot_lights'
89
+
90
+ # Initialize controller
91
+ controller = TuyaIotLights::SmartLightController.new(
92
+ client_id,
93
+ secret,
94
+ device_id
95
+ )
96
+
97
+ # Change color
98
+ controller.change_color('blue')
99
+
100
+ # Switch to white mode
101
+ controller.switch_to_white_mode
102
+
103
+ # Check available colors
104
+ TuyaIotLights::ColorPalette.available_colors
105
+ # => ["red", "orange", "yellow", ...]
106
+
107
+ # Get color HSV values
108
+ TuyaIotLights::ColorPalette.get_color('blue')
109
+ # => {"h"=>240, "s"=>1000, "v"=>1000}
110
+ ```
111
+
112
+ ## Current Limitations
113
+
114
+ **This gem currently supports basic RGB light control only:**
115
+
116
+ - ✅ **Color Changes**: Set lights to predefined colors (red, blue, green, etc.)
117
+ - ✅ **White Mode**: Switch to `work_mode=white` for standard white lighting
118
+ - ❌ **Other Device Types**: Only tested with Tuya RGB lights
119
+ - ❌ **Advanced Features**: No support for brightness, effects, scheduling, etc.
120
+ - ❌ **Multiple Devices**: Single device control only
121
+
122
+ **Supported API Calls:**
123
+ - `colour_data_v2` - Change light color using HSV values
124
+ - `work_mode` - Switch between color and white modes
125
+
126
+ ## Extending the Gem
127
+
128
+ **Want to add more features?** I welcome pull requests! 🎉
129
+
130
+ Some ideas for contributions:
131
+ - Support for brightness control
132
+ - Multiple device management
133
+ - Different Tuya device types (switches, sensors, etc.)
134
+ - Advanced lighting effects
135
+ - Scheduling and automation features
136
+ - Support for other Tuya API endpoints
137
+
138
+ See the [Contributing](#contributing) section below to get started.
139
+
140
+ ## Security
141
+
142
+ ### Credential Storage
143
+
144
+ - **CLI Mode**: Credentials are stored in `~/.tuya_iot_lights/config.yml` with 600 file permissions (owner read/write only)
145
+ - **Programmatic Mode**: Credentials are passed directly to constructors and **never stored to disk**
146
+ - **Safe YAML Loading**: Uses `YAML.safe_load` to prevent code execution when reading CLI config
147
+
148
+ ### Security Features
149
+
150
+ - **Input Validation**: All inputs are validated before processing
151
+ - **SSL Verification**: All API requests use SSL certificate verification
152
+ - **Request Timeouts**: HTTP requests have 30-second timeouts to prevent hanging
153
+ - **Hidden Input**: Secret credentials are hidden during CLI configuration (when terminal supports it)
154
+ - **No Hardcoded Secrets**: No default or fallback credentials in the codebase
155
+
156
+ ## Programmatic Usage
157
+
158
+ For Ruby applications, you can use the gem programmatically. **Note: When using the gem in your code, credentials are passed directly and never stored to disk:**
159
+
160
+ ```ruby
161
+ require 'tuya_iot_lights'
162
+
163
+ # Initialize controller with credentials (not stored anywhere)
164
+ controller = TuyaIotLights::SmartLightController.new(
165
+ 'your_client_id', # Pass directly - never stored
166
+ 'your_secret', # Pass directly - never stored
167
+ 'your_device_id' # Pass directly - never stored
168
+ )
169
+
170
+ # Control the light
171
+ controller.change_color('blue')
172
+ controller.switch_to_white_mode
173
+
174
+ # You can also use environment variables for security
175
+ controller = TuyaIotLights::SmartLightController.new(
176
+ ENV['TUYA_CLIENT_ID'],
177
+ ENV['TUYA_SECRET'],
178
+ ENV['TUYA_DEVICE_ID']
179
+ )
180
+ ```
181
+
182
+ **Security Note**: The `SmartLightController` class requires credentials as constructor parameters and does not read from or write to any configuration files. This ensures your credentials remain under your application's control.
183
+
184
+ ## Development
185
+
186
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
187
+
188
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
189
+
190
+ ## Contributing
191
+
192
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ksix/tuya_iot_lights! 🚀
193
+
194
+ ### How to Contribute
195
+
196
+ 1. **Fork the repository**
197
+ 2. **Create a feature branch** (`git checkout -b feature/amazing-feature`)
198
+ 3. **Add tests** for your new functionality
199
+ 4. **Ensure all tests pass** (`bundle exec rake test`)
200
+ 5. **Update documentation** as needed
201
+ 6. **Commit your changes** (`git commit -am 'Add amazing feature'`)
202
+ 7. **Push to the branch** (`git push origin feature/amazing-feature`)
203
+ 8. **Open a Pull Request**
204
+
205
+ ### Extension Ideas
206
+
207
+ **API Extensions:**
208
+ ```ruby
209
+ # Brightness control
210
+ controller.set_brightness(75) # 0-100%
211
+
212
+ # Multiple devices
213
+ controller.add_device('device_id_2')
214
+ controller.change_all_colors('red')
215
+
216
+ # Advanced features
217
+ controller.set_effect('rainbow')
218
+ controller.schedule_color('blue', at: '20:00')
219
+ ```
220
+
221
+ **Device Support:**
222
+ - Smart switches and plugs
223
+ - Temperature/humidity sensors
224
+ - Door/window sensors
225
+ - Smart curtains/blinds
226
+
227
+ ### Code Structure
228
+
229
+ - `lib/tuya_iot_lights/tuya_api_client.rb` - Add new API endpoints here
230
+ - `lib/tuya_iot_lights/smart_light_controller.rb` - Add new device control methods
231
+ - `lib/tuya_iot_lights/cli.rb` - Add new CLI commands
232
+ - `test/` - Add comprehensive tests for new features
233
+
234
+ This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/ksix/tuya_iot_lights/blob/main/CODE_OF_CONDUCT.md).
235
+
236
+ ## License
237
+
238
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
239
+
240
+ ## Code of Conduct
241
+
242
+ Everyone interacting in the TuyaIotLights project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/ksix/tuya_iot_lights/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "standard/rake"
9
+
10
+ task default: %i[test standard]
data/exe/tuya_light ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'tuya_iot_lights'
5
+
6
+ TuyaIotLights::CLI.run
@@ -0,0 +1,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'yaml'
4
+ require 'fileutils'
5
+ require 'io/console'
6
+
7
+ module TuyaIotLights
8
+ class CLI
9
+ CONFIG_DIR = File.expand_path('~/.tuya_iot_lights')
10
+ CONFIG_FILE = File.join(CONFIG_DIR, 'config.yml')
11
+
12
+ class ConfigurationError < StandardError; end
13
+
14
+ def self.run
15
+ command = ARGV[0]
16
+
17
+ case command
18
+ when 'configure'
19
+ configure
20
+ when '--help', '-h', 'help'
21
+ display_help
22
+ exit 0
23
+ when '--colors', 'colors'
24
+ ColorPalette.display_available_colors
25
+ exit 0
26
+ else
27
+ # Color command
28
+ color_name = command || "purple"
29
+ change_light_color(color_name.downcase)
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ def self.configure
36
+ puts "🔧 Tuya IoT Lights Configuration"
37
+ puts "Please enter your Tuya Cloud API credentials:"
38
+
39
+ print "Client ID: "
40
+ client_id = get_secure_input
41
+
42
+ print "Secret (hidden): "
43
+ secret = get_secure_input(hidden: true)
44
+
45
+ print "Device ID: "
46
+ device_id = get_secure_input
47
+
48
+ validate_credentials!(client_id, secret, device_id)
49
+
50
+ config = {
51
+ 'client_id' => client_id,
52
+ 'secret' => secret,
53
+ 'device_id' => device_id
54
+ }
55
+
56
+ save_config(config)
57
+ puts "✅ Configuration saved successfully!"
58
+ puts "You can now use: tuya_light [color] to control your lights"
59
+ end
60
+
61
+ def self.change_light_color(color_name)
62
+ config = load_config
63
+
64
+ unless config
65
+ puts "❌ No configuration found. Please run 'tuya_light configure' first."
66
+ exit 1
67
+ end
68
+
69
+ # Create controller and change color
70
+ controller = SmartLightController.new(
71
+ config['client_id'],
72
+ config['secret'],
73
+ config['device_id']
74
+ )
75
+
76
+ success = controller.change_color(color_name)
77
+ exit(success ? 0 : 1)
78
+ end
79
+
80
+ def self.save_config(config)
81
+ FileUtils.mkdir_p(CONFIG_DIR)
82
+ File.write(CONFIG_FILE, config.to_yaml)
83
+ File.chmod(0600, CONFIG_FILE) # Restrict access to owner only
84
+ end
85
+
86
+ def self.load_config
87
+ return nil unless File.exist?(CONFIG_FILE)
88
+
89
+ # Use safe_load to prevent code execution
90
+ YAML.safe_load(File.read(CONFIG_FILE), permitted_classes: [], permitted_symbols: [], aliases: false)
91
+ rescue => e
92
+ puts "❌ Error loading configuration: #{e.message}"
93
+ nil
94
+ end
95
+
96
+ def self.get_secure_input(hidden: false)
97
+ if hidden && STDIN.tty?
98
+ input = STDIN.noecho(&:gets)
99
+ puts # Add newline after hidden input
100
+ else
101
+ input = STDIN.gets
102
+ end
103
+
104
+ return "" unless input
105
+ input.chomp.strip
106
+ end
107
+
108
+ def self.validate_credentials!(client_id, secret, device_id)
109
+ errors = []
110
+
111
+ errors << "Client ID is required" if client_id.empty?
112
+ errors << "Secret is required" if secret.empty?
113
+ errors << "Device ID is required" if device_id.empty?
114
+
115
+ # Basic format validation
116
+ unless client_id.empty? || client_id.match?(/\A[a-zA-Z0-9]{10,}\z/)
117
+ errors << "Client ID format appears invalid"
118
+ end
119
+
120
+ unless device_id.empty? || device_id.match?(/\A[a-zA-Z0-9]{10,}\z/)
121
+ errors << "Device ID format appears invalid"
122
+ end
123
+
124
+ unless errors.empty?
125
+ puts "❌ Configuration errors:"
126
+ errors.each { |error| puts " - #{error}" }
127
+ exit 1
128
+ end
129
+ end
130
+
131
+ def self.display_help
132
+ puts <<~HELP
133
+ Tuya IoT Lights Controller
134
+
135
+ USAGE:
136
+ tuya_light configure # Set up your Tuya API credentials
137
+ tuya_light [COLOR] # Change light color
138
+ tuya_light [OPTIONS] # Show information
139
+
140
+ COMMANDS:
141
+ configure # Configure API credentials
142
+
143
+ ARGUMENTS:
144
+ COLOR # Color name to set the light to
145
+ # Use 'normal' to switch to white mode
146
+
147
+ OPTIONS:
148
+ --colors, colors # List all available colors
149
+ --help, -h, help # Show this help message
150
+
151
+ EXAMPLES:
152
+ tuya_light configure # Set up credentials
153
+ tuya_light blue # Set light to blue
154
+ tuya_light normal # Switch to white mode
155
+ tuya_light --colors # List available colors
156
+
157
+ CONFIGURATION:
158
+ Configuration is stored in ~/.tuya_iot_lights/config.yml
159
+ Run 'tuya_light configure' to set up your credentials
160
+
161
+ For more information, visit: https://github.com/ksix/tuya_iot_lights
162
+ HELP
163
+ end
164
+ end
165
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TuyaIotLights
4
+ class ColorPalette
5
+ COLORS = {
6
+ "red" => { "h" => 0, "s" => 1000, "v" => 1000 },
7
+ "orange" => { "h" => 30, "s" => 1000, "v" => 1000 },
8
+ "yellow" => { "h" => 60, "s" => 1000, "v" => 1000 },
9
+ "green" => { "h" => 120, "s" => 1000, "v" => 1000 },
10
+ "cyan" => { "h" => 180, "s" => 1000, "v" => 1000 },
11
+ "blue" => { "h" => 240, "s" => 1000, "v" => 1000 },
12
+ "purple" => { "h" => 270, "s" => 1000, "v" => 1000 },
13
+ "magenta" => { "h" => 300, "s" => 1000, "v" => 1000 },
14
+ "pink" => { "h" => 330, "s" => 700, "v" => 1000 },
15
+ "white" => { "h" => 0, "s" => 0, "v" => 1000 },
16
+ "warm_white" => { "h" => 30, "s" => 200, "v" => 1000 },
17
+ "cool_white" => { "h" => 200, "s" => 100, "v" => 1000 }
18
+ }.freeze
19
+
20
+ def self.available_colors
21
+ COLORS.keys
22
+ end
23
+
24
+ def self.get_color(name)
25
+ COLORS[name.downcase]
26
+ end
27
+
28
+ def self.valid_color?(name)
29
+ COLORS.key?(name.downcase)
30
+ end
31
+
32
+ def self.display_available_colors
33
+ puts "\n🎨 Available colors:"
34
+ COLORS.keys.each { |color| puts " - #{color}" }
35
+ puts "\n🤍 Special modes:"
36
+ puts " - normal (switches to white mode)"
37
+ puts "\nUsage: ruby light.rb [color_name|normal]"
38
+ puts "Example: ruby light.rb blue"
39
+ puts "Example: ruby light.rb normal"
40
+ end
41
+ end
42
+ end
43
+
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TuyaIotLights
4
+ class SmartLightController
5
+ def initialize(client_id, secret, device_id)
6
+ @api_client = TuyaApiClient.new(client_id, secret)
7
+ @device_id = device_id
8
+ end
9
+
10
+ def change_color(color_name)
11
+ # Check if switching to white mode
12
+ if color_name == "normal"
13
+ return switch_to_white_mode
14
+ end
15
+
16
+ # Validate color
17
+ unless ColorPalette.valid_color?(color_name)
18
+ puts "❌ Unknown color: #{color_name}"
19
+ ColorPalette.display_available_colors
20
+ puts "\nOr use 'normal' to switch to white mode"
21
+ return false
22
+ end
23
+
24
+ color_hsv = ColorPalette.get_color(color_name)
25
+ display_color_info(color_name, color_hsv)
26
+
27
+ # Get authentication token
28
+ access_token = @api_client.get_access_token
29
+ return false unless access_token
30
+
31
+ # Send color command
32
+ @api_client.send_color_command(@device_id, color_name, color_hsv, access_token)
33
+ end
34
+
35
+ def switch_to_white_mode
36
+ puts "🤍 Switching to normal (white) mode..."
37
+
38
+ # Get authentication token
39
+ access_token = @api_client.get_access_token
40
+ return false unless access_token
41
+
42
+ # Send white mode command
43
+ @api_client.send_white_mode_command(@device_id, access_token)
44
+ end
45
+
46
+ private
47
+
48
+ def display_color_info(color_name, color_hsv)
49
+ puts "🎨 Selected color: #{color_name.capitalize}"
50
+ puts " HSV values: H:#{color_hsv['h']}, S:#{color_hsv['s']}, V:#{color_hsv['v']}"
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,228 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'net/http'
4
+ require 'uri'
5
+ require 'json'
6
+ require 'digest'
7
+ require 'openssl'
8
+ require 'timeout'
9
+
10
+ module TuyaIotLights
11
+ class TuyaApiClient
12
+ API_BASE_URL = 'https://openapi.tuyaus.com'
13
+ TOKEN_ENDPOINT = '/v1.0/token'
14
+ REQUEST_TIMEOUT = 30 # seconds
15
+
16
+ class ApiError < StandardError; end
17
+ class AuthenticationError < ApiError; end
18
+ class NetworkError < ApiError; end
19
+
20
+ attr_reader :client_id
21
+
22
+ def initialize(client_id, secret)
23
+ @client_id = client_id
24
+ @secret = secret
25
+ end
26
+
27
+ def get_access_token
28
+ puts "🔐 Authenticating with Tuya API..."
29
+
30
+ timestamp = current_timestamp
31
+ url = "#{API_BASE_URL}#{TOKEN_ENDPOINT}?grant_type=1"
32
+
33
+ signature = generate_signature('GET', TOKEN_ENDPOINT + '?grant_type=1', '', timestamp)
34
+ headers = build_headers(signature, timestamp)
35
+
36
+ response = make_request('GET', url, headers)
37
+ parse_token_response(response)
38
+ end
39
+
40
+ def send_color_command(device_id, color_name, color_hsv, access_token)
41
+ puts "\n🎨 Sending color command (#{color_name.capitalize})..."
42
+
43
+ timestamp = current_timestamp
44
+ endpoint = "/v1.0/iot-03/devices/#{device_id}/commands"
45
+ url = "#{API_BASE_URL}#{endpoint}"
46
+
47
+ body = build_color_command_body(color_hsv)
48
+ signature = generate_signature('POST', endpoint, body, timestamp, access_token)
49
+ headers = build_headers(signature, timestamp, access_token, 'application/json')
50
+
51
+ response = make_request('POST', url, headers, body)
52
+ parse_command_response(response, color_name)
53
+ end
54
+
55
+ def send_white_mode_command(device_id, access_token)
56
+ puts "\n🤍 Switching to white mode..."
57
+
58
+ timestamp = current_timestamp
59
+ endpoint = "/v1.0/iot-03/devices/#{device_id}/commands"
60
+ url = "#{API_BASE_URL}#{endpoint}"
61
+
62
+ body = build_white_mode_command_body
63
+ signature = generate_signature('POST', endpoint, body, timestamp, access_token)
64
+ headers = build_headers(signature, timestamp, access_token, 'application/json')
65
+
66
+ response = make_request('POST', url, headers, body)
67
+ parse_white_mode_response(response)
68
+ end
69
+
70
+ private
71
+
72
+ def current_timestamp
73
+ (Time.now.to_f * 1000).to_i.to_s
74
+ end
75
+
76
+ def generate_signature(method, path, body, timestamp, access_token = '')
77
+ content_hash = Digest::SHA256.hexdigest(body)
78
+ string_to_sign = [ method, content_hash, '', path ].join("\n")
79
+ sign_str = "#{@client_id}#{access_token}#{timestamp}#{string_to_sign}"
80
+
81
+ OpenSSL::HMAC.hexdigest('SHA256', @secret, sign_str).upcase
82
+ end
83
+
84
+ def build_headers(signature, timestamp, access_token = nil, content_type = nil)
85
+ headers = {
86
+ 'client_id' => @client_id,
87
+ 'sign' => signature,
88
+ 't' => timestamp,
89
+ 'sign_method' => 'HMAC-SHA256'
90
+ }
91
+
92
+ headers['access_token'] = access_token if access_token
93
+ headers['Content-Type'] = content_type if content_type
94
+
95
+ headers
96
+ end
97
+
98
+ def build_color_command_body(color_hsv)
99
+ {
100
+ "commands" => [
101
+ {
102
+ "code" => "colour_data_v2",
103
+ "value" => {
104
+ "h" => color_hsv["h"],
105
+ "s" => color_hsv["s"],
106
+ "v" => color_hsv["v"]
107
+ }
108
+ }
109
+ ]
110
+ }.to_json
111
+ end
112
+
113
+ def build_white_mode_command_body
114
+ {
115
+ "commands" => [
116
+ {
117
+ "code" => "work_mode",
118
+ "value" => "white"
119
+ }
120
+ ]
121
+ }.to_json
122
+ end
123
+
124
+ def make_request(method, url, headers, body = nil)
125
+ uri = URI(url)
126
+ http = Net::HTTP.new(uri.host, uri.port)
127
+ http.use_ssl = true
128
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER
129
+ http.open_timeout = REQUEST_TIMEOUT
130
+ http.read_timeout = REQUEST_TIMEOUT
131
+
132
+ request = case method
133
+ when 'GET'
134
+ Net::HTTP::Get.new(uri.request_uri)
135
+ when 'POST'
136
+ Net::HTTP::Post.new(uri.request_uri)
137
+ else
138
+ raise ArgumentError, "Unsupported HTTP method: #{method}"
139
+ end
140
+
141
+ headers.each { |key, value| request[key] = value }
142
+ request.body = body if body
143
+
144
+ response = http.request(request)
145
+
146
+ unless response.code.start_with?('2')
147
+ puts "❌ HTTP Error: #{response.code} #{response.message}"
148
+ return nil
149
+ end
150
+
151
+ response
152
+ rescue Net::ReadTimeout, Net::OpenTimeout => e
153
+ puts "❌ Request timeout: #{e.message}"
154
+ nil
155
+ rescue OpenSSL::SSL::SSLError => e
156
+ puts "❌ SSL Error: #{e.message}"
157
+ nil
158
+ rescue => e
159
+ puts "❌ Network error: #{e.message}"
160
+ nil
161
+ end
162
+
163
+ def parse_token_response(response)
164
+ return nil unless response&.code == "200"
165
+
166
+ begin
167
+ json_response = JSON.parse(response.body)
168
+ if json_response["success"]
169
+ access_token = json_response.dig('result', 'access_token')
170
+ expire_time = json_response.dig('result', 'expire_time')
171
+ puts "✅ Authentication successful! Token expires in #{expire_time} seconds"
172
+ access_token
173
+ else
174
+ puts "❌ Authentication failed: #{json_response['msg']} (Code: #{json_response['code']})"
175
+ display_auth_troubleshooting
176
+ nil
177
+ end
178
+ rescue JSON::ParserError
179
+ puts "❌ Invalid response format"
180
+ nil
181
+ end
182
+ end
183
+
184
+ def parse_command_response(response, color_name)
185
+ return false unless response&.code == "200"
186
+
187
+ begin
188
+ json_response = JSON.parse(response.body)
189
+ if json_response["success"]
190
+ puts "✅ Color changed to #{color_name} successfully! 🎉"
191
+ true
192
+ else
193
+ puts "❌ Command failed: #{json_response['msg']} (Code: #{json_response['code']})"
194
+ false
195
+ end
196
+ rescue JSON::ParserError
197
+ puts "❌ Invalid response format"
198
+ false
199
+ end
200
+ end
201
+
202
+ def parse_white_mode_response(response)
203
+ return false unless response&.code == "200"
204
+
205
+ begin
206
+ json_response = JSON.parse(response.body)
207
+ if json_response["success"]
208
+ puts "✅ Switched to white mode successfully! 🤍"
209
+ true
210
+ else
211
+ puts "❌ Command failed: #{json_response['msg']} (Code: #{json_response['code']})"
212
+ false
213
+ end
214
+ rescue JSON::ParserError
215
+ puts "❌ Invalid response format"
216
+ false
217
+ end
218
+ end
219
+
220
+ def display_auth_troubleshooting
221
+ puts "\n🔧 Possible issues:"
222
+ puts "1. Invalid client_id or secret"
223
+ puts "2. Client credentials not properly configured in Tuya Cloud"
224
+ puts "3. Incorrect API endpoint region (using US region)"
225
+ puts "4. Account/project not properly set up for API access"
226
+ end
227
+ end
228
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TuyaIotLights
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "tuya_iot_lights/version"
4
+ require_relative "tuya_iot_lights/color_palette"
5
+ require_relative "tuya_iot_lights/tuya_api_client"
6
+ require_relative "tuya_iot_lights/smart_light_controller"
7
+ require_relative "tuya_iot_lights/cli"
8
+
9
+ module TuyaIotLights
10
+ class Error < StandardError; end
11
+ class ConfigurationError < Error; end
12
+ class ApiError < Error; end
13
+ class AuthenticationError < ApiError; end
14
+ class NetworkError < ApiError; end
15
+ end
@@ -0,0 +1,4 @@
1
+ module TuyaIotLights
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,122 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: tuya_iot_lights
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Matt Hinczuk
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-07-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: vcr
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '6.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '6.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: webmock
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '13.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '13.0'
69
+ description: Control Tuya IoT smart lights with easy color changes and white mode
70
+ switching through the Tuya Cloud API. Provides both CLI and programmatic interfaces
71
+ with secure credential management.
72
+ email:
73
+ - matiasmoya@gmail.com
74
+ executables:
75
+ - tuya_light
76
+ extensions: []
77
+ extra_rdoc_files: []
78
+ files:
79
+ - ".standard.yml"
80
+ - CHANGELOG.md
81
+ - CODE_OF_CONDUCT.md
82
+ - LICENSE.txt
83
+ - README.md
84
+ - Rakefile
85
+ - exe/tuya_light
86
+ - lib/tuya_iot_lights.rb
87
+ - lib/tuya_iot_lights/cli.rb
88
+ - lib/tuya_iot_lights/color_palette.rb
89
+ - lib/tuya_iot_lights/smart_light_controller.rb
90
+ - lib/tuya_iot_lights/tuya_api_client.rb
91
+ - lib/tuya_iot_lights/version.rb
92
+ - sig/tuya_iot_lights.rbs
93
+ homepage: https://github.com/matiasmoya/tuya_iot_lights
94
+ licenses:
95
+ - MIT
96
+ metadata:
97
+ bug_tracker_uri: https://github.com/matiasmoya/tuya_iot_lights/issues
98
+ documentation_uri: https://github.com/matiasmoya/tuya_iot_lights#readme
99
+ funding_uri: https://github.com/sponsors/matiasmoya
100
+ homepage_uri: https://github.com/matiasmoya/tuya_iot_lights
101
+ source_code_uri: https://github.com/matiasmoya/tuya_iot_lights
102
+ changelog_uri: https://github.com/matiasmoya/tuya_iot_lights/blob/main/CHANGELOG.md
103
+ post_install_message:
104
+ rdoc_options: []
105
+ require_paths:
106
+ - lib
107
+ required_ruby_version: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - ">="
110
+ - !ruby/object:Gem::Version
111
+ version: 3.0.0
112
+ required_rubygems_version: !ruby/object:Gem::Requirement
113
+ requirements:
114
+ - - ">="
115
+ - !ruby/object:Gem::Version
116
+ version: '0'
117
+ requirements: []
118
+ rubygems_version: 3.5.16
119
+ signing_key:
120
+ specification_version: 4
121
+ summary: A Ruby gem for controlling Tuya IoT smart lights
122
+ test_files: []