takagi 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: a3dbe9feeb83c1626cf6c518a2b42c80d8cc5d20c7b6c4cb88c53df425be6427
4
+ data.tar.gz: ab8e5225fcaba27dbdc3a743eeff33b44a9f8f6b66f169212d62a9b01b5b9308
5
+ SHA512:
6
+ metadata.gz: f63adf24e94b8b87a333742405ca77d450861ffaa028879f603f01e8731700dc1358fc0aa1a486e0715cec984c91b17ca970ae8354f8ac4a5f6ae757ec291be8
7
+ data.tar.gz: 6e933738a7102e970480566238caf888444ee1016e564176241b3d7598cd5b404d5e979769c4ab234b1b53803fb14cf031e7b2b8fca135cb3442b504e5783b01
data/.idea/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
data/.idea/misc.xml ADDED
@@ -0,0 +1,4 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectRootManager" version="2" project-jdk-name="ruby-3.1.2-p20" project-jdk-type="RUBY_SDK" />
4
+ </project>
data/.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/takagi.iml" filepath="$PROJECT_DIR$/.idea/takagi.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
data/.idea/takagi.iml ADDED
@@ -0,0 +1,81 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="RUBY_MODULE" version="4">
3
+ <component name="ModuleRunConfigurationManager">
4
+ <shared />
5
+ </component>
6
+ <component name="NewModuleRootManager">
7
+ <content url="file://$MODULE_DIR$">
8
+ <sourceFolder url="file://$MODULE_DIR$/features" isTestSource="true" />
9
+ <sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
10
+ <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
11
+ </content>
12
+ <orderEntry type="inheritedJdk" />
13
+ <orderEntry type="sourceFolder" forTests="false" />
14
+ <orderEntry type="library" scope="PROVIDED" name="ast (v2.4.2, ruby-3.1.2-p20) [gem]" level="application" />
15
+ <orderEntry type="library" scope="PROVIDED" name="bigdecimal (v3.1.9, ruby-3.1.2-p20) [gem]" level="application" />
16
+ <orderEntry type="library" scope="PROVIDED" name="bundler (v2.5.6, ruby-3.1.2-p20) [gem]" level="application" />
17
+ <orderEntry type="library" scope="PROVIDED" name="diff-lcs (v1.6.0, ruby-3.1.2-p20) [gem]" level="application" />
18
+ <orderEntry type="library" scope="PROVIDED" name="json (v2.10.1, ruby-3.1.2-p20) [gem]" level="application" />
19
+ <orderEntry type="library" scope="PROVIDED" name="language_server-protocol (v3.17.0.4, ruby-3.1.2-p20) [gem]" level="application" />
20
+ <orderEntry type="library" scope="PROVIDED" name="lint_roller (v1.1.0, ruby-3.1.2-p20) [gem]" level="application" />
21
+ <orderEntry type="library" scope="PROVIDED" name="parallel (v1.26.3, ruby-3.1.2-p20) [gem]" level="application" />
22
+ <orderEntry type="library" scope="PROVIDED" name="parser (v3.3.7.1, ruby-3.1.2-p20) [gem]" level="application" />
23
+ <orderEntry type="library" scope="PROVIDED" name="racc (v1.8.1, ruby-3.1.2-p20) [gem]" level="application" />
24
+ <orderEntry type="library" scope="PROVIDED" name="rack (v3.1.10, ruby-3.1.2-p20) [gem]" level="application" />
25
+ <orderEntry type="library" scope="PROVIDED" name="rainbow (v3.1.1, ruby-3.1.2-p20) [gem]" level="application" />
26
+ <orderEntry type="library" scope="PROVIDED" name="rake (v13.2.1, ruby-3.1.2-p20) [gem]" level="application" />
27
+ <orderEntry type="library" scope="PROVIDED" name="regexp_parser (v2.10.0, ruby-3.1.2-p20) [gem]" level="application" />
28
+ <orderEntry type="library" scope="PROVIDED" name="rspec (v3.13.0, ruby-3.1.2-p20) [gem]" level="application" />
29
+ <orderEntry type="library" scope="PROVIDED" name="rspec-core (v3.13.3, ruby-3.1.2-p20) [gem]" level="application" />
30
+ <orderEntry type="library" scope="PROVIDED" name="rspec-expectations (v3.13.3, ruby-3.1.2-p20) [gem]" level="application" />
31
+ <orderEntry type="library" scope="PROVIDED" name="rspec-mocks (v3.13.2, ruby-3.1.2-p20) [gem]" level="application" />
32
+ <orderEntry type="library" scope="PROVIDED" name="rspec-support (v3.13.2, ruby-3.1.2-p20) [gem]" level="application" />
33
+ <orderEntry type="library" scope="PROVIDED" name="rubocop (v1.73.0, ruby-3.1.2-p20) [gem]" level="application" />
34
+ <orderEntry type="library" scope="PROVIDED" name="rubocop-ast (v1.38.1, ruby-3.1.2-p20) [gem]" level="application" />
35
+ <orderEntry type="library" scope="PROVIDED" name="ruby-progressbar (v1.13.0, ruby-3.1.2-p20) [gem]" level="application" />
36
+ <orderEntry type="library" scope="PROVIDED" name="sequel (v5.89.0, ruby-3.1.2-p20) [gem]" level="application" />
37
+ <orderEntry type="library" scope="PROVIDED" name="unicode-display_width (v3.1.4, ruby-3.1.2-p20) [gem]" level="application" />
38
+ <orderEntry type="library" scope="PROVIDED" name="unicode-emoji (v4.0.4, ruby-3.1.2-p20) [gem]" level="application" />
39
+ </component>
40
+ <component name="RakeTasksCache-v2">
41
+ <option name="myRootTask">
42
+ <RakeTaskImpl id="rake">
43
+ <subtasks>
44
+ <RakeTaskImpl description="Build takagi-0.1.0.gem into the pkg directory" fullCommand="build" id="build" />
45
+ <RakeTaskImpl id="build">
46
+ <subtasks>
47
+ <RakeTaskImpl description="Generate SHA512 checksum if takagi-0.1.0.gem into the checksums directory" fullCommand="build:checksum" id="checksum" />
48
+ </subtasks>
49
+ </RakeTaskImpl>
50
+ <RakeTaskImpl description="Remove any temporary products" fullCommand="clean" id="clean" />
51
+ <RakeTaskImpl description="Remove any generated files" fullCommand="clobber" id="clobber" />
52
+ <RakeTaskImpl description="Build and install takagi-0.1.0.gem into system gems" fullCommand="install" id="install" />
53
+ <RakeTaskImpl id="install">
54
+ <subtasks>
55
+ <RakeTaskImpl description="Build and install takagi-0.1.0.gem into system gems without network access" fullCommand="install:local" id="local" />
56
+ </subtasks>
57
+ </RakeTaskImpl>
58
+ <RakeTaskImpl description="Create tag v0.1.0 and build and push takagi-0.1.0.gem to https://rubygems.org" fullCommand="release[remote]" id="release[remote]" />
59
+ <RakeTaskImpl description="Run RuboCop" fullCommand="rubocop" id="rubocop" />
60
+ <RakeTaskImpl id="rubocop">
61
+ <subtasks>
62
+ <RakeTaskImpl description="Autocorrect RuboCop offenses (only when it's safe)" fullCommand="rubocop:autocorrect" id="autocorrect" />
63
+ <RakeTaskImpl description="Autocorrect RuboCop offenses (safe and unsafe)" fullCommand="rubocop:autocorrect_all" id="autocorrect_all" />
64
+ <RakeTaskImpl description="" fullCommand="rubocop:auto_correct" id="auto_correct" />
65
+ </subtasks>
66
+ </RakeTaskImpl>
67
+ <RakeTaskImpl description="Run RSpec code examples" fullCommand="spec" id="spec" />
68
+ <RakeTaskImpl description="" fullCommand="default" id="default" />
69
+ <RakeTaskImpl description="" fullCommand="release" id="release" />
70
+ <RakeTaskImpl id="release">
71
+ <subtasks>
72
+ <RakeTaskImpl description="" fullCommand="release:guard_clean" id="guard_clean" />
73
+ <RakeTaskImpl description="" fullCommand="release:rubygem_push" id="rubygem_push" />
74
+ <RakeTaskImpl description="" fullCommand="release:source_control_push" id="source_control_push" />
75
+ </subtasks>
76
+ </RakeTaskImpl>
77
+ </subtasks>
78
+ </RakeTaskImpl>
79
+ </option>
80
+ </component>
81
+ </module>
data/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.0
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-02-26
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at domitea@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dominik Matoulek
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,110 @@
1
+ # Takagi – Lightweight CoAP Framework for Ruby
2
+
3
+ <!---
4
+ [![Gem Version](https://badge.fury.io/rb/takagi.svg)](https://rubygems.org/gems/takagi)
5
+ -->
6
+ [![Build Status](https://github.com/domitea/takagi/actions/workflows/main.yml/badge.svg)](https://github.com/domitea/takagi/actions)
7
+
8
+ ## About Takagi
9
+
10
+ **Takagi** is a **Sinatra-like CoAP framework** for IoT and microservices in Ruby.
11
+ It provides a lightweight way to build **CoAP APIs**, handle **IoT messaging**, and process sensor data efficiently.
12
+
13
+ 🔹 **Minimalistic DSL** – Define CoAP endpoints just like in Sinatra.
14
+ 🔹 **Efficient and fast** – Runs over UDP, ideal for IoT applications.
15
+ 🔹 **Database-ready** – Seamless integration with **Sequel** for storing device data.
16
+
17
+ ---
18
+
19
+ ## Installation
20
+
21
+ Add this line to your application's Gemfile:
22
+
23
+ ```ruby
24
+ gem 'takagi'
25
+ ```
26
+
27
+ Or install it manually:
28
+
29
+ ```sh
30
+ gem install takagi
31
+ ```
32
+
33
+ ---
34
+
35
+ ## Getting Started
36
+
37
+ ### **Create a new Takagi API**
38
+ ```ruby
39
+ require 'takagi'
40
+
41
+ class SensorAPI < Takagi::Base
42
+ get "/sensor/:id" do |params|
43
+ Sensor[params[:id].to_i].to_json
44
+ end
45
+
46
+ post "/sensor" do |params|
47
+ Sensor.create(params).to_json
48
+ end
49
+ end
50
+
51
+ Takagi.run!
52
+ ```
53
+ 🔥 **Boom! You just built a CoAP API in Ruby.**
54
+
55
+ ---
56
+
57
+ ## Sending Requests
58
+
59
+ ### **Using `coap-client`**
60
+ ```sh
61
+ coap-client -m get coap://localhost:5683/sensor/1
62
+ ```
63
+ ```sh
64
+ coap-client -m post coap://localhost:5683/sensor -e '{"value":42}'
65
+ ```
66
+
67
+ ---
68
+
69
+ ## Features & Modules
70
+
71
+ | Feature | Description | Status |
72
+ |-----------------|--------------------------------|--------|
73
+ | **CoAP API** | Define REST-like CoAP routes | ✅ Ready |
74
+ | **Sequel DB** | Store IoT data in PostgreSQL, SQLite, etc. | ✅ Ready |
75
+ | **Notifications** | Redis, HTTP, ZeroMQ messaging | 🔄 WIP |
76
+ | **Buffering** | Store messages before processing | 🔄 Planned |
77
+ | **Compression** | Reduce payload size | 🔄 Planned |
78
+
79
+ ---
80
+
81
+ ## Roadmap
82
+
83
+ ✅ **Core framework (CoAP, Sequel, notifications)**
84
+ 🔜 **Web UI for data visualization**
85
+ 🔜 **More integrations: NATS, MQTT...**
86
+
87
+ ---
88
+
89
+ ## Contributing
90
+
91
+ Want to help? Fork the repo and submit a PR!
92
+
93
+ ```sh
94
+ git clone https://github.com/domitea/takagi.git
95
+ cd takagi
96
+ bundle install
97
+ ```
98
+
99
+ Run tests:
100
+ ```sh
101
+ rspec
102
+ ```
103
+
104
+ ---
105
+
106
+ ## License
107
+
108
+ **MIT License**
109
+
110
+ ---
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rack"
4
+ require "sequel"
5
+ require "socket"
6
+ require "json"
7
+
8
+ require_relative "router"
9
+ require_relative "message"
10
+ require_relative "server"
11
+
12
+ module Takagi
13
+ class Base < Takagi::Router
14
+ def self.run!(port: 5683)
15
+ Takagi::Server.run!(port: port)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'logger'
4
+
5
+ module Takagi
6
+ class Logger
7
+ @logger = ::Logger.new($stdout)
8
+ @logger.level = ::Logger::INFO
9
+
10
+ def self.set_level(level)
11
+ @logger.level = level
12
+ end
13
+
14
+ def self.info(message)
15
+ @logger.info(message)
16
+ end
17
+
18
+ def self.debug(message)
19
+ @logger.debug(message)
20
+ end
21
+
22
+ def self.error(message)
23
+ @logger.error(message)
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Takagi
4
+ class Message
5
+ def self.parse(data)
6
+ version_type_tkl = data.bytes[0]
7
+ code = data.bytes[1]
8
+ data.bytes[2..3].pack("C*").unpack1("n")
9
+ token_length = version_type_tkl & 0x0F
10
+ token = data[4, token_length] || "".b
11
+ path = extract_uri_path(data.bytes[(4 + token_length)..])
12
+ payload_start = data.index("\xFF".b)
13
+ payload = payload_start ? data[(payload_start + 1)..].force_encoding("ASCII-8BIT") : nil
14
+
15
+ { method: coap_code_to_method(code), path: path, token: token, payload: payload }
16
+ end
17
+
18
+ def self.build_response(code, payload, token)
19
+ message_id = rand(0..0xFFFF)
20
+ response_code = coap_method_to_code(code)
21
+ header = [0x60 | (token.bytesize & 0x0F), response_code, (message_id >> 8) & 0xFF, message_id & 0xFF].pack("C*")
22
+
23
+ payload_marker = "\xFF".b
24
+ payload_data = payload.to_json.force_encoding("ASCII-8BIT")
25
+ header + token + payload_marker + payload_data
26
+ end
27
+
28
+ def self.coap_code_to_method(code)
29
+ case code
30
+ when 1 then "GET"
31
+ when 2 then "POST"
32
+ when 3 then "PUT"
33
+ when 4 then "DELETE"
34
+ else "UNKNOWN"
35
+ end
36
+ end
37
+
38
+ def self.coap_method_to_code(code)
39
+ case code
40
+ when 2.05 then 69 # 2.05 Content
41
+ when 4.04 then 132 # 4.04 Not Found
42
+ else 160 # Generic response
43
+ end
44
+ end
45
+
46
+ def self.extract_uri_path(bytes)
47
+ path_segments = [] # Místo prostého stringu uložíme segmenty do pole
48
+ options_start = 0
49
+ last_option = 0
50
+
51
+ while options_start < bytes.length && bytes[options_start] != 255 # 0xFF = start payloadu
52
+ delta = (bytes[options_start] >> 4) & 0x0F # Číslo opce
53
+ len = bytes[options_start] & 0x0F # Délka dat
54
+ options_start += 1
55
+
56
+ option_number = last_option + delta
57
+ if option_number == 11 # Uri-Path (11 znamená část cesty)
58
+ segment = bytes[options_start, len].pack("C*").b
59
+ path_segments << segment # Ukládáme jednotlivé segmenty do pole
60
+ puts "Parsed path segment: #{segment}" # Debug výpis
61
+ end
62
+
63
+ options_start += len
64
+ last_option = option_number
65
+ end
66
+
67
+ # Spojíme segmenty pomocí `/` a zajistíme, že začne `/`
68
+ path = "/#{path_segments.join("/")}"
69
+
70
+ path.force_encoding("UTF-8") if path.valid_encoding?
71
+ puts "Final parsed path: #{path}" # Debug výpis celé cesty
72
+ path
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Takagi
4
+ class Router
5
+ @@routes = {}
6
+
7
+ def self.get(path, &block)
8
+ @@routes["GET #{path}"] = block
9
+ end
10
+
11
+ def self.post(path, &block)
12
+ @@routes["POST #{path}"] = block
13
+ end
14
+
15
+ def self.find_route(method, path)
16
+ return @@routes["#{method} #{path}"], {} if @@routes.key?("#{method} #{path}")
17
+
18
+ match_dynamic_route(method, path)
19
+ end
20
+
21
+ def self.match_dynamic_route(method, path)
22
+ @@routes.each do |route_key, block|
23
+ route_method, route_path = route_key.split(" ", 2)
24
+ next unless route_method == method
25
+
26
+ route_parts = route_path.split("/")
27
+ path_parts = path.split("/")
28
+ next unless route_parts.length == path_parts.length
29
+
30
+ params = {}
31
+ match = route_parts.each_with_index.all? do |part, index|
32
+ if part.start_with?(":")
33
+ param_name = part[1..]
34
+ params[param_name.to_sym] = path_parts[index]
35
+ true
36
+ else
37
+ part == path_parts[index]
38
+ end
39
+ end
40
+
41
+ return [block, params] if match
42
+ end
43
+
44
+ [nil, {}]
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "logger"
4
+
5
+ module Takagi
6
+ class Server
7
+ LOGGER = Takagi::Logger
8
+
9
+ def self.run!(port: 5683)
10
+ server = UDPSocket.new
11
+ server.bind("0.0.0.0", port)
12
+ LOGGER.info("Takagi running on CoAP://0.0.0.0:#{port}")
13
+
14
+ loop do
15
+ data, addr = server.recvfrom(1024)
16
+ request = Message.parse(data)
17
+
18
+ LOGGER.info("Request: #{request[:method]} #{request[:path]}, Token: #{request[:token].unpack("H*").first}")
19
+
20
+ route, params = Router.find_route(request[:method], request[:path])
21
+ response = if route
22
+ params.merge!(JSON.parse(request[:payload])) if request[:payload]
23
+ route.call(params)
24
+ else
25
+ LOGGER.error("Route not found: #{request[:method]} #{request[:path]}")
26
+ { error: "Not Found" }
27
+ end
28
+
29
+ response_data = Message.build_response(2.05, response, request[:token])
30
+ LOGGER.info("Response: 2.05 Content -> #{response.to_json}")
31
+
32
+ server.send(response_data, 0, addr[3], addr[1])
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Takagi
4
+ VERSION = "0.1.0"
5
+ end
data/lib/takagi.rb ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "takagi/version"
4
+ require_relative "takagi/base"
5
+
6
+ module Takagi
7
+ class Error < StandardError; end
8
+ # Your code goes here...
9
+ end
data/sig/takagi.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Takagi
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
data/takagi.gemspec ADDED
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/takagi/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "takagi"
7
+ spec.version = Takagi::VERSION
8
+ spec.authors = ["Dominik Matoulek"]
9
+ spec.email = ["domitea@gmail.com"]
10
+
11
+ spec.summary = "Lightweight CoAP framework for Ruby"
12
+ spec.description = "Sinatra-like framework for CoAP and IoT messaging."
13
+ spec.homepage = "https://github.com/domitea/takagi"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.0.0"
16
+
17
+ spec.metadata["allowed_push_host"] ||= "https://rubygems.org"
18
+
19
+ spec.metadata["homepage_uri"] = spec.homepage
20
+ spec.metadata["source_code_uri"] = "https://github.com/domitea/takagi"
21
+ spec.metadata["changelog_uri"] = "https://github.com/domitea/takagi/CHANGELOG.md"
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(__dir__) do
26
+ `git ls-files -z`.split("\x0").reject do |f|
27
+ (File.expand_path(f) == __FILE__) ||
28
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile])
29
+ end
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ # Uncomment to register a new dependency of your gem
36
+ # spec.add_dependency "example-gem", "~> 1.0"
37
+ spec.add_dependency "rack"
38
+ spec.add_dependency "sequel"
39
+
40
+ spec.add_development_dependency "rspec"
41
+
42
+ # For more information and examples about making a new gem, check out our
43
+ # guide at: https://bundler.io/guides/creating_gem.html
44
+ end
metadata ADDED
@@ -0,0 +1,110 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: takagi
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Dominik Matoulek
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-02-26 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rack
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: sequel
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: Sinatra-like framework for CoAP and IoT messaging.
56
+ email:
57
+ - domitea@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".idea/.gitignore"
63
+ - ".idea/misc.xml"
64
+ - ".idea/modules.xml"
65
+ - ".idea/takagi.iml"
66
+ - ".idea/vcs.xml"
67
+ - ".rspec"
68
+ - ".rubocop.yml"
69
+ - CHANGELOG.md
70
+ - CODE_OF_CONDUCT.md
71
+ - LICENSE.txt
72
+ - README.md
73
+ - Rakefile
74
+ - lib/takagi.rb
75
+ - lib/takagi/base.rb
76
+ - lib/takagi/logger.rb
77
+ - lib/takagi/message.rb
78
+ - lib/takagi/router.rb
79
+ - lib/takagi/server.rb
80
+ - lib/takagi/version.rb
81
+ - sig/takagi.rbs
82
+ - takagi.gemspec
83
+ homepage: https://github.com/domitea/takagi
84
+ licenses:
85
+ - MIT
86
+ metadata:
87
+ allowed_push_host: https://rubygems.org
88
+ homepage_uri: https://github.com/domitea/takagi
89
+ source_code_uri: https://github.com/domitea/takagi
90
+ changelog_uri: https://github.com/domitea/takagi/CHANGELOG.md
91
+ post_install_message:
92
+ rdoc_options: []
93
+ require_paths:
94
+ - lib
95
+ required_ruby_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: 3.0.0
100
+ required_rubygems_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - ">="
103
+ - !ruby/object:Gem::Version
104
+ version: '0'
105
+ requirements: []
106
+ rubygems_version: 3.3.7
107
+ signing_key:
108
+ specification_version: 4
109
+ summary: Lightweight CoAP framework for Ruby
110
+ test_files: []