<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Halil İbrahim Direktör on Medium]]></title>
        <description><![CDATA[Stories by Halil İbrahim Direktör on Medium]]></description>
        <link>https://medium.com/@hidirektor?source=rss-896b10891d87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pRGAE6vaIuqW7coMAGl2cA@2x.jpeg</url>
            <title>Stories by Halil İbrahim Direktör on Medium</title>
            <link>https://medium.com/@hidirektor?source=rss-896b10891d87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 21:35:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hidirektor/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Guess It’s Red: A One-Year Retrospective on Expensive Architectural Decisions]]></title>
            <link>https://medium.com/@hidirektor/i-guess-its-red-a-one-year-retrospective-on-expensive-architectural-decisions-5ea048d170d8?source=rss-896b10891d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ea048d170d8</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Halil İbrahim Direktör]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 20:05:03 GMT</pubDate>
            <atom:updated>2026-02-20T20:07:37.487Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the last year, most of my architectural decisions came from a “red” instinct: optimizing for stability, operational control, and predictable delivery. I leaned into bootstrap-first flows, stricter middleware boundaries, explicit service ownership, and infrastructure choices that reduced production surprises.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Z3NWbDOmz-EagwlUBrcEjQ.jpeg" /><figcaption>Of course, there were plot twists, surprise regressions and a few “this was not in the architecture diagram” moments.</figcaption></figure><p><strong>Soo firstly, here is my precious tech stack lately:</strong></p><p>Frontend: Next.js, React, TypeScript, Context + store state patterns, Socket.IO client<br>Backend: Node.js, Express, Sequelize, Redis, Socket.IO, cluster-based background processing<br>Data and integration: SQL-centered core data with migration runners and event/listener flows<br>Infrastructure: Docker, Terraform, cloud services for queues, object storage, secrets, and monitoring</p><p>And the toolchain around it: <a href="https://apidog.com/">Apidog</a> (API design/testing), <a href="https://dbdiagram.io/home">dbdiagram</a> (schema modeling), almost the full <a href="https://jetbrains.com/">JetBrains</a> IDE suite (<a href="https://www.jetbrains.com/webstorm/">WebStorm</a>, <a href="https://www.jetbrains.com/datagrip/">DataGrip</a>, etc.), and <a href="https://clickup.com/">ClickUp</a> (planning, execution, and delivery tracking).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*yyDY7yCU1op_x7iqoxMsPQ.png" /></figure><p>The key lesson: jetbrains is everywhere no no just kidding the real one is expensive architecture is rarely about one technology; it is about coupling across layers.</p><h3>What Is This “Red” Thing? (Red, Black, and a Third Pattern)</h3><p>Yegor Bugayenko’s red vs black framing still resonates:</p><ul><li><strong>Red</strong>: optimize for order, control, and compliance</li><li><strong>Black</strong>: optimize for outcomes, speed, and customer pull</li></ul><p>Over the last year, I also saw a third category:</p><ul><li><strong>Mirror</strong>: decisions primarily optimized for architect satisfaction</li></ul><p>Mirror is dangerous because it often looks like “good engineering” while delivering weak business impact.</p><p>Also if you guys did not read Red vs. Black from Yegor Bugayenko you must read from <a href="https://www.yegor256.com/2025/09/14/red-and-black.html">his blog</a>.</p><h3>Why I Drifted Toward Red or Why I’m Describing Myself as a Red One</h3><p>Because the domains demanded it:</p><ul><li>Strong RBAC and permission boundaries</li><li>Strict session/token handling</li><li>Real-time behavior with operational traceability</li><li>High uptime expectations</li><li>Safe data evolution under active traffic</li></ul><p>In that context, red was often the right call. But even right decisions accumulate cost.</p><h3><strong>So Lets Begin…</strong></h3><h3>1) Bootstrap-First Startup Architecture</h3><p><strong>What I did:</strong> I designed services to initialize almost everything upfront: configuration, caches, DB pools, model registries, queues, listeners, and runtime dependencies.</p><p><strong>Why it looked right:</strong> It aligned with “fail fast” and deterministic startup. Production readiness became predictable, and the system avoided “half-alive” states.</p><p><strong>What actually happened:</strong> Startup became a single dependency bottleneck. One unstable integration (network, broker, third-party) could delay the entire service — even if that dependency was optional.</p><p><strong>What I’d do now:</strong></p><ul><li>Split initialization into <strong>Tier-0 (critical)</strong> vs <strong>Tier-1/2 (optional)</strong> startup paths.</li><li>Bring the service up with a minimal viable runtime, then warm up optional dependencies in the background.</li><li>Support <strong>controlled degraded modes</strong> when non-critical dependencies are unhealthy.</li><li>Separate health signals: <strong>liveness ≠ readiness ≠ dependency health</strong>.</li></ul><h3>2) Middleware-Heavy Request Lifecycle</h3><p><strong>What I did:</strong> I pushed auth, localization, device metadata, timezone handling, cache-control, auditing, and response normalization into long middleware chains.</p><p><strong>Why it looked right:</strong> It standardized cross-cutting policies and reduced duplication across controllers.</p><p><strong>What actually happened:</strong> Traceability suffered. Debugging became order-dependent and expensive — understanding “why this request behaved this way” required mentally simulating middleware interactions, which increased regression risk.</p><p><strong>What I’d do now:</strong></p><ul><li>Keep middleware <strong>thin</strong> (correlation IDs, basic logging, simple validation).</li><li>Move business-sensitive behavior into <strong>explicit services</strong> with clear boundaries.</li><li>Add structured tracing/annotations so pipeline effects are observable by default.</li></ul><h3>3) Convention-Driven Dynamic Routing</h3><p><strong>What I did:</strong> I favored convention-based route discovery/mounting over fully explicit route registration.</p><p><strong>Why it looked right:</strong> It reduced boilerplate and accelerated onboarding as the API surface expanded.</p><p><strong>What actually happened:</strong> Ownership and discoverability dropped. Route behavior became harder to reason about quickly (“where is this route defined?” and “who owns it?” were no longer obvious).</p><p><strong>What I’d do now:</strong></p><ul><li>Keep conventions, but generate an <strong>explicit route manifest</strong>.</li><li>Validate the manifest in CI (diffs, auth rules, versioning, naming, ownership).</li><li>Use the same manifest to drive documentation and operational visibility.</li></ul><h3>4) Real-Time by Default (WebSocket + Cluster-Aware Runtime)</h3><p><strong>What I did:</strong> For many flows, I defaulted to real-time channels and a clustered runtime rather than single-process execution.</p><p><strong>Why it looked right:</strong> It promised better concurrency, fault isolation, and availability under load.</p><p><strong>What actually happened:</strong> The coordination overhead was significant: sticky sessions, inter-process coordination, state fan-out, and more complex observability. For low-traffic services, the complexity wasn’t justified.</p><p><strong>What I’d do now:</strong></p><ul><li>Use cluster mode only where traffic and latency profiles justify it.</li><li>Keep low-traffic services single-process for simplicity and reliability.</li><li>Prefer clearer patterns like stateless edges + shared pub/sub for socket state when needed.</li></ul><h3>5) Tight Session/Token Coupling Across Layers</h3><p><strong>What I did:</strong> Client session behavior was tightly aligned with backend token TTL and auth semantics.</p><p><strong>Why it looked right:</strong> It enforced security consistency and reduced drift between frontend and backend authentication behavior.</p><p><strong>What actually happened:</strong> Small auth changes cascaded into UX side effects and increased regression risk. Token policy adjustments became product-visible behavior changes.</p><p><strong>What I’d do now:</strong></p><ul><li>Treat session semantics as a <strong>versioned contract</strong>, not an implicit implementation detail.</li><li>Roll out auth changes with compatibility windows and feature flags.</li><li>Make token/session behavior explicit and testable as part of the API contract.</li></ul><h3>6) Migration-Safe Data Evolution Over Delivery Speed</h3><p><strong>What I did:</strong> I prioritized idempotent, ordered, low-risk migration pipelines.</p><p><strong>Why it looked right:</strong> It improved safety under live traffic and increased rollback confidence.</p><p><strong>What actually happened:</strong> Feature rollout slowed down and coexistence windows became long, creating drag and accumulating operational complexity.</p><p><strong>What I’d do now:</strong></p><ul><li>Pair conservative migrations with <strong>strict deprecation windows</strong>.</li><li>Use feature-flagged cutovers and commit to explicit sunset dates.</li><li>Enforce backward/forward compatibility with automated tests and release gates.</li></ul><h3>The Core Insight From This Year</h3><p>The most expensive architectural decisions are rarely wrong on day one.<br>They become expensive when context changes faster than the architecture.</p><p>My recurring issue was not making bad decisions.<br>It was keeping previously-good defaults for too long.</p><h3>The 3 Questions I Use Now</h3><p>Before committing to an architectural direction, I ask:</p><ol><li>Will this still be adaptable in six months if constraints shift?</li><li>Can the team explain and debug it quickly during an incident?</li><li>Is the value measurable in reliability, delivery, or user impact?</li></ol><p>If I cannot answer all three, it is probably a preference, not architecture.</p><h3>I still guess it’s red.</h3><p>But now I treat red as a bias, not an identity.</p><p>Architecture discipline is powerful.<br>Used well, it scales systems.<br>Used blindly, it scales friction.</p><p>The real skill is not choosing red or black.<br>It is knowing when to switch before your architecture becomes your bottleneck.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ea048d170d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Native Android Development: A Developer’s Pre-Launch Checklist]]></title>
            <link>https://medium.com/@hidirektor/native-android-development-a-developers-pre-launch-checklist-db3ecc2d44f5?source=rss-896b10891d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/db3ecc2d44f5</guid>
            <category><![CDATA[relese-android-app]]></category>
            <category><![CDATA[app-releases]]></category>
            <category><![CDATA[native-development]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Halil İbrahim Direktör]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 10:37:41 GMT</pubDate>
            <atom:updated>2025-04-06T10:45:08.758Z</atom:updated>
            <content:encoded><![CDATA[<p>Publishing a native Android application is a time of immense achievement, a culmination of countless hours coding, designing, and testing. Yet, the journey from a functional build to a successful Play Store debut is littered with pitfalls ready to derail the app’s success. Skipping crucial pre-launch testing can lead to negative user reviews, technical debt, and thus, tepid adoption of the app. This checklist, based on years of field experience and a disciplined software development methodology, aims to provide a comprehensive guide for native Android developers as they prepare for that crucial “Go Live” milestone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9aEUWhBU3uDLR0NZwecsw.png" /><figcaption>Source: <a href="https://www.checklistsformanagers.com/checklist/release-deployment-checklist">Check List for Managers</a></figcaption></figure><h3>I. Performance and Stability: Providing a Seamless User Experience</h3><p>A performant and stable application is the cornerstone of user satisfaction. Before even considering a beta release, the following aspects must be carefully analyzed:</p><ul><li><strong>Memory Management and Leak Detection:</strong> Android’s resource-constrained environment necessitates diligent memory management. Employing profiling tools like Android Studio’s Memory Profiler is crucial to identify and rectify memory leaks. These insidious issues can lead to OutOfMemoryError crashes, especially on low-end devices or during prolonged usage. Regularly running instrumentation tests focusing on long-running operations and activity transitions can help uncover subtle leaks. Furthermore, integrating static analysis tools that specifically flag potential memory management issues should be a standard practice.</li><li><strong>CPU and Battery Optimization:</strong> Excessive CPU usage translates directly to battery drain and a sluggish user experience. Utilize Android Studio’s CPU Profiler to pinpoint performance bottlenecks. Optimize computationally intensive tasks by employing efficient algorithms, offloading work to background threads using WorkManager or Coroutines, and minimizing unnecessary UI updates. Battery drain is a major user concern; therefore, rigorously test the app&#39;s power consumption under various usage scenarios. Tools like Battery Historian can provide detailed insights into power usage patterns, enabling targeted optimizations.</li><li><strong>Crash Reporting and Analytics Integration:</strong> Proactive identification and resolution of crashes are essential. Integrate a robust crash reporting library (e.g., Firebase Crashlytics, Sentry) to capture detailed stack traces and device information. Configure comprehensive analytics (e.g., Google Analytics for Firebase) to track user behavior, identify frequently used features, and pinpoint areas where errors or unexpected behavior might be occurring. Analyzing these reports during internal testing and beta releases is crucial for iterative refinement.</li><li><strong>UI Responsiveness and Jank Reduction:</strong> A fluid and responsive user interface is critical for engagement. Utilize Android Studio’s Frame Rate Monitor and Systrace to identify and address UI jank. Optimize custom views, minimize overdraw, and ensure that long-running operations are never performed on the main thread. Employ asynchronous operations and appropriate threading models to maintain UI responsiveness even under heavy load.</li></ul><h3>II. Functionality and Compatibility: Delivering on Promises</h3><p>The core functionality of the application must be thoroughly tested across a range of devices and Android versions:</p><ul><li><strong>Comprehensive Unit and Integration Testing:</strong> Implement a robust suite of unit tests to verify the correctness of individual components and integration tests to ensure that different parts of the application work seamlessly together. Aim for high code coverage, focusing on critical business logic and edge cases. Employ testing frameworks like JUnit, Mockito, and Espresso for UI testing. Continuous integration pipelines should automatically run these tests upon every code change.</li><li><strong>Device and Android Version Compatibility Testing:</strong> Android’s fragmented ecosystem necessitates rigorous testing on a diverse set of physical devices representing different manufacturers, screen sizes, resolutions, and Android versions (aligning with the app’s declared minSdkVersion and targetSdkVersion). Utilize device farms (e.g., Firebase Test Lab, BrowserStack) to augment physical device testing. Pay close attention to platform-specific behavior and ensure graceful degradation of features on older Android versions if necessary.</li><li><strong>Network Connectivity Handling:</strong> Applications relying on network communication must handle various network conditions gracefully, including loss of connectivity, slow connections, and intermittent failures. Implement appropriate error handling, retry mechanisms (with exponential backoff), and offline support where feasible. Thoroughly test the app’s behavior under different network scenarios, including airplane mode and simulated network latency.</li><li><strong>Background Process Testing:</strong> Applications utilizing background services, broadcast receivers, or scheduled jobs (using WorkManager) must be rigorously tested to ensure they function correctly even when the app is not in the foreground or after device reboots. Pay close attention to battery optimization restrictions introduced in newer Android versions and adapt background processing strategies accordingly.</li></ul><h3>III. Security and Privacy: Building User Trust</h3><p>Security and privacy are non-negotiable aspects of modern mobile applications:</p><ul><li><strong>Data Security and Encryption:</strong> Sensitive data must be protected both in transit and at rest. Utilize secure communication protocols (HTTPS) for all network requests. Encrypt locally stored sensitive data using Android’s security APIs (e.g., EncryptedSharedPreferences, Keystore). Implement appropriate data sanitization and validation techniques to prevent common security vulnerabilities like SQL injection and cross-site scripting (if WebView is used).</li><li><strong>Permissions Management:</strong> Adhere to the principle of least privilege by requesting only the necessary permissions. Clearly explain the purpose of each permission request to the user. Handle permission denials gracefully and provide alternative functionality or explanations. Thoroughly test the app’s behavior with and without granted permissions.</li><li><strong>Third-Party Library Security:</strong> Regularly review and update all third-party libraries and SDKs used in the application to address known security vulnerabilities. Be aware of the permissions and potential data collection practices of these dependencies. Employ tools that scan for known vulnerabilities in project dependencies.</li><li><strong>Privacy Policy Compliance:</strong> Ensure that the application’s privacy policy is comprehensive, clearly outlines the data collected, how it is used, and with whom it is shared. The policy must be easily accessible within the app and comply with relevant data privacy regulations (e.g., GDPR, CCPA).</li></ul><h3>IV. User Experience and Presentation: Polishing the Final Product</h3><p>A well-designed and user-friendly interface is crucial for user retention:</p><ul><li><strong>User Interface (UI) and User Experience (UX) Review:</strong> Conduct thorough usability testing with representative users to identify any pain points or areas for improvement in the user interface and overall user experience. Ensure adherence to Android’s Material Design guidelines for consistency and intuitiveness. Pay close attention to navigation, information architecture, and accessibility.</li><li><strong>Localization and Internationalization (if applicable):</strong> If the app targets a global audience, ensure proper localization of all text content, including strings, dates, times, and currencies. Test the app on devices with different locales to identify any layout issues or right-to-left (RTL) language support problems.</li><li><strong>Accessibility Testing:</strong> Make the application accessible to users with disabilities by implementing features like content descriptions for images, proper labeling of UI elements, and support for assistive technologies like TalkBack and Select to Speak. Utilize Android Studio’s Accessibility Scanner to identify potential accessibility issues.</li><li><strong>Visual Appeal and Branding Consistency:</strong> Ensure that the application’s visual design is polished, consistent with the brand identity, and visually appealing across different screen sizes and densities. Pay attention to typography, color palettes, and the overall aesthetic.</li></ul><h3>V. Store Listing and Distribution: Preparing for Launch</h3><p>The final steps involve preparing the app’s presence on the Google Play Store:</p><ul><li><strong>Compelling Store Listing:</strong> Craft a compelling and informative app title, short description, and long description that accurately reflects the app’s features and benefits. Include relevant keywords to improve discoverability. Provide high-quality screenshots and a promotional video that showcase the app’s key features and user interface.</li><li><strong>App Metadata and Categorization:</strong> Select appropriate app categories and tags to ensure that the app is listed correctly in the Play Store. Provide accurate contact information and a link to the privacy policy.</li><li><strong>Release Management and Versioning:</strong> Establish a clear versioning strategy (e.g., semantic versioning) and carefully manage the release process through the Google Play Console. Consider using staged rollouts to gradually release the app to a subset of users, allowing for early detection and resolution of any unforeseen issues.</li><li><strong>Beta Testing Program:</strong> Conduct a thorough beta testing program with a diverse group of users to gather feedback, identify bugs, and validate the app’s stability and usability in a real-world environment. Utilize the Google Play Console’s beta testing features for efficient management of beta testers and feedback collection.</li></ul><h3>Conclusion</h3><p>Launching a successful native Android application requires meticulous planning, rigorous testing, and attention to detail across various critical areas. This pre-launch checklist serves as a comprehensive guide for developers to systematically address potential issues related to performance, stability, functionality, security, user experience, and store listing. By diligently adhering to these checks, developers can significantly increase the likelihood of a smooth and successful launch, ultimately leading to positive user reception and long-term app success in the competitive Android ecosystem. The investment in thorough pre-launch preparation is not merely a task to be completed but a strategic imperative for building a high-quality and sustainable mobile application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db3ecc2d44f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify Server Setup with Docker Launcher Script]]></title>
            <link>https://medium.com/@hidirektor/simplify-server-setup-with-docker-launcher-script-1a5716466609?source=rss-896b10891d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a5716466609</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-launcher]]></category>
            <dc:creator><![CDATA[Halil İbrahim Direktör]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 18:13:29 GMT</pubDate>
            <atom:updated>2025-03-25T18:13:29.288Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up a server with Docker can feel overwhelming — installing dependencies, configuring containers, and keeping everything running smoothly takes time and effort. Enter the **Docker Setup Script**, a Bash tool that automates the heavy lifting. This script sets up a robust Docker environment with services like Portainer, Nginx Proxy Manager, MariaDB, phpMyAdmin, and Duplicati, all manageable through an intuitive menu. Let’s dive into what it offers, how it operates, and why it’s worth a try.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZLKulKy6TB-KrzmtUvtgSw.jpeg" /><figcaption>Source: <a href="https://www.silviodibenedetto.com/docker-automation-with-dockerfile/">Silvio Di Benedetto</a></figcaption></figure><h3><strong>What’s in the Package?</strong></h3><p>The Launcher script is built to simplify server management by:<br>-<strong> Bootstrapping Docker:</strong> Installs Docker and Docker Compose if they’re missing.<br>- <strong>Deploying a Service Stack: </strong>Launches a collection of tools for hosting and administration.<br>- <strong>Providing Control:</strong> Offers options to install, fix, reset, or refresh your setup.<br>- <strong>Customizing Easily:</strong> Relies on a `.env` file to tweak settings like domains and credentials. The lineup of services includes:<br>- <strong>Portainer: </strong>A dashboard for overseeing Docker containers. — **Nginx**: A fast, reliable web server.<br>- <strong>Nginx Proxy Manager:</strong> A user-friendly reverse proxy with SSL capabilities.<br>- <strong>MariaDB:</strong> A powerful database solution.<br>- <strong>phpMyAdmin:</strong> A web interface for database administration.<br>- <strong>Duplicati: </strong>A backup system to safeguard your data.</p><h3><strong>How Does It Work?</strong></h3><p>Written in Bash, the script takes a step-by-step approach:</p><p>1. Environment Setup: It searches for a `.env` file and generates a template if none exists, ready for your custom inputs.<br>2. Validation: Checks that all necessary variables (e.g., admin names, passwords) are defined.<br>3. Docker Prep: Ensures Docker is active, installing it if needed.<br>4. Service Configuration: Builds a `docker-compose.yml` file with all services and their settings.<br>5. Interactive Menu: Lets you pick from options like a full install or a quick repair.</p><p><strong>For a fresh install, it:</strong><br>- Sets up Docker and Compose.<br>- Creates a Compose file in a directory like `/opt/docker/yourdomain.com`.<br>- Starts all services with a single `docker-compose up -d` command.<br>- Outputs access details like URLs and login info.</p><h3><strong>Why Choose This Script?</strong></h3><p>- <strong>Efficiency: </strong>Cuts down setup time from hours to minutes.<br>- <strong>Robustness: </strong>Includes safeguards against errors, like missing variables or Docker hiccups.<br>- <strong>Flexibility: </strong>Supports maintenance tasks like updates or resets alongside initial setups.<br>- <strong>Accessibility: </strong>A clear menu makes it approachable, even for Docker newcomers.</p><h3>Ho<strong>w to Get Started</strong></h3><p>Ready to give it a spin? Here’s the process:</p><ul><li><strong>Grab the Code:</strong></li></ul><pre>git clone https://github.com/hidirektor/docker_launcher.git<br> cd docker_launcher</pre><ul><li><strong>Launch the Script:</strong></li></ul><pre>chmod +x launcher.sh<br>./launcher.sh # Start Launcher Setup Script</pre><ul><li><strong>Tune the </strong>.env<strong> File: </strong>Update the generated .env with your preferences — think domain names, passwords, and more.</li><li><strong>Make Your Move: </strong>Select “1” for a new setup and let the script do its thing.</li></ul><p>When it’s done, you’ll get a handy summary like:<br><strong>Server IP: </strong>192.168.1.100<br><strong>Portainer: </strong><a href="http://192.168.1.100:9000/">http://192.168.1.100:9000</a><br><strong>Nginx Proxy Manager:</strong> <a href="http://192.168.1.100:81/">http://192.168.1.100:81</a><br><strong>phpMyAdmin:</strong> <a href="http://192.168.1.100:8183/">http://192.168.1.100:8183</a></p><h3><strong>Pro Tips</strong></h3><p><strong>Adjust Paths:</strong> Tweak the docker-compose.yml file for custom backup or config locations.<br><strong>Stay Secure:</strong> Use strong, unique passwords in your .env.<br><strong>Expand It: </strong>Add more services to the Compose file to fit your needs.</p><p><strong>Wrapping Up</strong><br>The Launcher Docker Setup Script is a game-changer for anyone wanting a quick, reliable way to spin up a Docker-powered server. From web hosting to backups, it’s got you covered with minimal fuss. You can explore the full details and grab the script on <a href="https://github.com/hidirektor/docker_launcher/tree/main">GitHub</a> — give it a go and share your thoughts!</p><h4>Happy server-building!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a5716466609" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Secure Time-Series IoT Solution: InfluxDB, Node.js, and Telegraf with Docker]]></title>
            <link>https://medium.com/@hidirektor/building-a-secure-time-series-iot-solution-influxdb-node-js-and-telegraf-with-docker-3a1fb90db9b1?source=rss-896b10891d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a1fb90db9b1</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[real-time-data]]></category>
            <dc:creator><![CDATA[Halil İbrahim Direktör]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 22:06:04 GMT</pubDate>
            <atom:updated>2025-02-28T22:10:04.763Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How to Run InfluxDB in Docker: A Practical Guide</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_-SToMetquNywS1S-nb-w.png" /><figcaption>InfluxDB (<a href="https://www.influxdata.com/products/influxdb-overview/">Click for the image source</a>)</figcaption></figure><h3>Introduction</h3><p>InfluxDB is a high-performance time-series database designed for handling time-stamped data, making it ideal for IoT applications, monitoring systems, and real-time analytics. In this expanded guide, we’ll deploy InfluxDB using Docker Compose via Portainer, build a secure Node.js backend with authentication, manage device registration and user-device pairing, and integrate Telegraf for automated data collection. We’ll also ensure scalability and security by pulling sensitive data from a<strong> .env</strong> file and validating bucket configurations with retention policies.</p><h3>Prerequisites</h3><p>Before proceeding, ensure you have the following installed:</p><ul><li><strong>Docker</strong>: Install from <a href="https://www.docker.com/">Docker’s official website</a>.</li><li><strong>Docker Compose</strong>: Typically bundled with Docker.</li><li><strong>Portainer</strong>: For managing Docker stacks on a remote server.</li><li><strong>Node.js and npm</strong>: For the backend application.</li><li><strong>Git</strong>: For version control (optional).</li></ul><h3>Step 1: Deploy InfluxDB and Telegraf using Docker Compose on Portainer</h3><p>We’ll deploy both InfluxDB and Telegraf (an agent for collecting and sending metrics) using a single docker-compose.yml. Create the file below and upload it to Portainer as a stack.</p><pre>version: &#39;3.7&#39;<br>services:<br>  influxdb:<br>    image: influxdb:latest<br>    container_name: influxdb<br>    ports:<br>      - &quot;8086:8086&quot;<br>    volumes:<br>      - influxdb_data:/var/lib/influxdb2<br>    environment:<br>      - INFLUXDB_DB=${INFLUXDB_DB}<br>      - INFLUXDB_ADMIN_USER=${INFLUXDB_ADMIN_USER}<br>      - INFLUXDB_ADMIN_PASSWORD=${INFLUXDB_ADMIN_PASSWORD}<br>      - INFLUXDB_TOKEN=${INFLUXDB_TOKEN}<br>      - INFLUXDB_ORG=${INFLUXDB_ORG}<br>      - INFLUXDB_BUCKET=${INFLUXDB_BUCKET}<br><br>  telegraf:<br>    image: telegraf:latest<br>    container_name: telegraf<br>    volumes:<br>      - ./telegraf.conf:/etc/telegraf/telegraf.conf:ro<br>    environment:<br>      - INFLUXDB_TOKEN=${INFLUXDB_TOKEN}<br>      - INFLUXDB_ORG=${INFLUXDB_ORG}<br>      - INFLUXDB_BUCKET=${INFLUXDB_BUCKET}<br>      - INFLUXDB_URL=http://influxdb:8086<br>    depends_on:<br>      - influxdb<br><br>volumes:<br>  influxdb_data:<br>    driver: local</pre><h4>Telegraf Configuration (telegraf.conf)</h4><p>Create a basic telegraf.conf file to collect system metrics and send them to InfluxDB:</p><pre>[agent]<br>  interval = &quot;10s&quot;<br>  flush_interval = &quot;10s&quot;<br><br>[[outputs.influxdb_v2]]<br>  urls = [&quot;http://influxdb:8086&quot;]<br>  token = &quot;$INFLUXDB_TOKEN&quot;<br>  organization = &quot;$INFLUXDB_ORG&quot;<br>  bucket = &quot;$INFLUXDB_BUCKET&quot;<br><br># Example: Collect data from an MQTT broker<br>[[inputs.mqtt_consumer]]<br>  servers = [&quot;tcp://your-mqtt-broker:1883&quot;]<br>  topics = [&quot;devices/#&quot;]<br>  data_format = &quot;json&quot;<br>  json_strict = true<br><br>  [[inputs.mqtt_consumer.json_transformation]]<br>    # Map MQTT JSON fields to InfluxDB fields<br>    tags = [&quot;deviceId&quot;, &quot;userId&quot;]<br>    fields = [&quot;location&quot;, &quot;status&quot;, &quot;voltage&quot;, &quot;current&quot;, &quot;temperature&quot;]</pre><h4>Environment Variables</h4><p>Create a .env file in your project root to store sensitive data:</p><pre># InfluxDB Configuration<br>INFLUXDB_URL=http://your-remote-server:8086<br>INFLUXDB_TOKEN=your-secret-token<br>INFLUXDB_ORG=your-org<br>INFLUXDB_BUCKET=device-data<br>INFLUXDB_ADMIN_USER=admin<br>INFLUXDB_ADMIN_PASSWORD=securepassword123<br>INFLUXDB_BUCKET_RETENTION=30d<br><br># Backend Configuration<br>PORT=3000<br>JWT_SECRET=your-jwt-secret</pre><p>Deploy the stack in Portainer, ensuring the .env file is available to substitute the variables.</p><h3>Step 2: Setting Up the Node.js Backend</h3><p>We’ll create a structured Node.js application with middleware, authentication, and bucket management.</p><pre>project-root/<br>├── src/<br>│   ├── config/<br>│   │   └── influxdb.js<br>│   ├── middleware/<br>│   │   └── auth.js<br>│   ├── models/<br>│   │   └── device.js<br>│   ├── routes/<br>│   │   └── device.js<br>│   ├── app.js<br>│   └── server.js<br>├── telegraf.conf<br>├── docker-compose.yml<br>├── .env<br>└── package.json</pre><h4>Install Dependencies</h4><p>Run the following command to install required packages:</p><pre>npm install @influxdata/influxdb-client express dotenv jsonwebtoken uuid helmet cors</pre><h4>Configuration (src/config/influxdb.js)</h4><p>This file initializes the InfluxDB client and ensures the bucket exists with the specified retention period.</p><pre>const { InfluxDB, Point } = require(&#39;@influxdata/influxdb-client&#39;);<br>const { BucketsAPI } = require(&#39;@influxdata/influxdb-client-apis&#39;);<br>require(&#39;dotenv&#39;).config();<br><br>const url = process.env.INFLUXDB_URL;<br>const token = process.env.INFLUXDB_TOKEN;<br>const org = process.env.INFLUXDB_ORG;<br>const bucket = process.env.INFLUXDB_BUCKET;<br>const retention = process.env.INFLUXDB_BUCKET_RETENTION;<br><br>const influxDB = new InfluxDB({ url, token });<br>const writeApi = influxDB.getWriteApi(org, bucket, &#39;ns&#39;);<br>const queryApi = influxDB.getQueryApi(org);<br><br>const setupBucket = async () =&gt; {<br>  const bucketsAPI = new BucketsAPI(influxDB);<br>  try {<br>    const buckets = await bucketsAPI.getBuckets({ org });<br>    const bucketExists = buckets.buckets.some((b) =&gt; b.name === bucket);<br>    if (!bucketExists) {<br>      await bucketsAPI.postBuckets({<br>        body: {<br>          name: bucket,<br>          orgID: (await bucketsAPI.getBuckets({ org })).buckets[0].orgID,<br>          retentionRules: [{ everySeconds: convertRetentionToSeconds(retention) }],<br>        },<br>      });<br>      console.log(`Bucket ${bucket} created with retention ${retention}`);<br>    } else {<br>      console.log(`Bucket ${bucket} already exists`);<br>    }<br>  } catch (error) {<br>    console.error(&#39;Error setting up bucket:&#39;, error);<br>  }<br>};<br><br>const convertRetentionToSeconds = (retention) =&gt; {<br>  const unit = retention.slice(-1);<br>  const value = parseInt(retention.slice(0, -1));<br>  switch (unit) {<br>    case &#39;d&#39;: return value * 86400;<br>    case &#39;h&#39;: return value * 3600;<br>    case &#39;m&#39;: return value * 60;<br>    default: return value;<br>  }<br>};<br><br>module.exports = { influxDB, writeApi, queryApi, bucket, org, setupBucket };</pre><h4>Device Model (src/models/device.js)</h4><p>Define a simple Device class for structuring data:</p><pre>class Device {<br>  constructor(deviceId, userId, location, status, voltage, current, temperature) {<br>    this.deviceId = deviceId;<br>    this.userId = userId;<br>    this.location = location;<br>    this.status = status;<br>    this.voltage = voltage;       // in volts (e.g., 3.3)<br>    this.current = current;       // in amperes (e.g., 0.5)<br>    this.temperature = temperature; // in Celsius (e.g., 25.5)<br>  }<br>}<br><br>module.exports = Device;</pre><h4>Authentication Middleware (src/middleware/auth.js)</h4><p>Protect routes with JWT-based authentication:</p><pre>const jwt = require(&#39;jsonwebtoken&#39;);<br>require(&#39;dotenv&#39;).config();<br><br>const auth = (req, res, next) =&gt; {<br>  const token = req.header(&#39;Authorization&#39;)?.replace(&#39;Bearer &#39;, &#39;&#39;);<br>  if (!token) return res.status(401).json({ message: &#39;No token provided&#39; });<br><br>  try {<br>    const decoded = jwt.verify(token, process.env.JWT_SECRET);<br>    req.user = decoded;<br>    next();<br>  } catch (error) {<br>    res.status(401).json({ message: &#39;Invalid token&#39; });<br>  }<br>};<br><br>module.exports = auth;</pre><h4>Routes (src/routes/device.js)</h4><p>Define API endpoints for device management:</p><pre>const express = require(&#39;express&#39;);<br>const { v4: uuidv4 } = require(&#39;uuid&#39;);<br>const { writeApi, queryApi, bucket } = require(&#39;../config/influxdb&#39;);<br>const auth = require(&#39;../middleware/auth&#39;);<br>const Device = require(&#39;../models/device&#39;);<br>const router = express.Router();<br><br>// Register a new device<br>router.post(&#39;/register-device&#39;, auth, async (req, res) =&gt; {<br>  const { location, status, voltage, current, temperature } = req.body;<br>  const deviceId = uuidv4();<br>  const userId = req.user.id;<br><br>  const device = new Device(deviceId, userId, location, status, voltage, current, temperature);<br>  const point = new Point(&#39;device&#39;)<br>    .tag(&#39;deviceId&#39;, device.deviceId)<br>    .tag(&#39;userId&#39;, device.userId)<br>    .stringField(&#39;location&#39;, device.location)<br>    .stringField(&#39;status&#39;, device.status)<br>    .floatField(&#39;voltage&#39;, device.voltage)<br>    .floatField(&#39;current&#39;, device.current)<br>    .floatField(&#39;temperature&#39;, device.temperature);<br><br>  writeApi.writePoint(point);<br>  await writeApi.close();<br>  res.json({ message: &#39;Device registered successfully&#39;, deviceId });<br>});<br><br>// Pair device with user<br>router.post(&#39;/pair-device&#39;, auth, async (req, res) =&gt; {<br>  const { deviceId } = req.body;<br>  const userId = req.user.id;<br><br>  const deviceData = await queryDeviceData(deviceId);<br>  if (!deviceData.length) {<br>    return res.status(404).json({ message: &#39;Device not found&#39; });<br>  }<br><br>  const existingDevice = deviceData[0];<br>  const point = new Point(&#39;device&#39;)<br>    .tag(&#39;deviceId&#39;, deviceId)<br>    .tag(&#39;userId&#39;, userId)<br>    .stringField(&#39;location&#39;, existingDevice.location)<br>    .stringField(&#39;status&#39;, &#39;paired&#39;)<br>    .floatField(&#39;voltage&#39;, existingDevice.voltage || 0) // Preserve existing values or default<br>    .floatField(&#39;current&#39;, existingDevice.current || 0)<br>    .floatField(&#39;temperature&#39;, existingDevice.temperature || 0);<br><br>  writeApi.writePoint(point);<br>  await writeApi.close();<br>  res.json({ message: &#39;Device paired successfully&#39; });<br>});<br><br>// Helper function to query device data<br>const queryDeviceData = (deviceId) =&gt; {<br>  const query = `from(bucket: &quot;${bucket}&quot;) <br>    |&gt; range(start: -30d) <br>    |&gt; filter(fn: (r) =&gt; r[&quot;deviceId&quot;] == &quot;${deviceId}&quot;) <br>    |&gt; last()`; // Use &#39;last()&#39; to get the most recent record<br>  return new Promise((resolve, reject) =&gt; {<br>    const results = [];<br>    queryApi.queryRows(query, {<br>      next(row, tableMeta) {<br>        const data = tableMeta.toObject(row);<br>        results.push({<br>          deviceId: data.deviceId,<br>          userId: data.userId,<br>          location: data.location,<br>          status: data.status,<br>          voltage: data.voltage,<br>          current: data.current,<br>          temperature: data.temperature,<br>        });<br>      },<br>      error(error) {<br>        reject(error);<br>      },<br>      complete() {<br>        resolve(results);<br>      },<br>    });<br>  });<br>};<br><br>module.exports = router;</pre><h4>Main Application (src/app.js)</h4><p>Set up Express with middleware and routes:</p><pre>const express = require(&#39;express&#39;);<br>const helmet = require(&#39;helmet&#39;);<br>const cors = require(&#39;cors&#39;);<br>const deviceRoutes = require(&#39;./routes/device&#39;);<br><br>const app = express();<br><br>app.use(helmet());<br>app.use(cors());<br>app.use(express.json());<br><br>app.use(&#39;/api/devices&#39;, deviceRoutes);<br><br>module.exports = app;</pre><h4>Server (src/server.js)</h4><p>Start the server and initialize InfluxDB:</p><pre>const app = require(&#39;./app&#39;);<br>const { setupBucket } = require(&#39;./config/influxdb&#39;);<br>require(&#39;dotenv&#39;).config();<br><br>const PORT = process.env.PORT || 3000;<br><br>const startServer = async () =&gt; {<br>  await setupBucket();<br>  app.listen(PORT, () =&gt; {<br>    console.log(`Server running on port ${PORT}`);<br>  });<br>};<br><br>startServer();</pre><h3>Step 3: Ensuring Data Integrity and Security</h3><ul><li><strong>Authentication</strong>: All endpoints are protected with JWT middleware.</li><li><strong>Bucket Management</strong>: The setupBucket function checks for and creates the bucket with the retention period from .env.</li><li><strong>Environment Variables</strong>: Sensitive data (e.g., tokens, credentials) is stored in .env and accessed securely.</li></ul><h3>Step 4: Running the Application</h3><ol><li>Start the Docker stack via Portainer.</li><li>Run the Node.js backend:</li><li>Test the API endpoints using a tool like Postman, including a JWT token in the Authorization header.</li></ol><h3>Conclusion</h3><p>In this guide, we’ve built a robust and secure time-series data solution tailored for IoT device management. By deploying InfluxDB and Telegraf via Docker Compose on Portainer, we established a scalable foundation for collecting and storing time-stamped metrics. The Node.js backend, enhanced with JWT authentication and environment-driven configuration, now efficiently handles device registration and user-device pairing while incorporating critical sensor data — voltage, current, and temperature — as float fields alongside location and status. These additions enable precise monitoring of electrical and environmental conditions, making the system well-suited for real-world applications like smart energy management, equipment health tracking, or indoor climate control.</p><h3>Next Steps</h3><ul><li><strong>Advanced Authentication</strong>: Much more specific authentication for the whole system.</li><li><strong>Data Validation</strong>: Input validation for voltage, current, and temperature (e.g., ranges like 0–24V, -50 to 100°C).</li><li><strong>Visualization</strong>: Grafana implementation to plot these metrics over time.</li><li><strong>Alerts</strong>: Setting up InfluxDB alerts for abnormal values (e.g., temperature &gt; 40°C).</li><li><strong>Notification Management</strong>: Implementation One Signal for inner notifications.</li></ul><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a1fb90db9b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Üzerinde RabbitMQ Çalıştırma ve NodeJS Entegrasyonu]]></title>
            <link>https://medium.com/@hidirektor/docker-%C3%BCzerinde-rabbitmq-%C3%A7al%C4%B1%C5%9Ft%C4%B1rma-ve-nodejs-entegrasyonu-fd1d66289cb7?source=rss-896b10891d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd1d66289cb7</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Halil İbrahim Direktör]]></dc:creator>
            <pubDate>Mon, 19 Aug 2024 09:28:51 GMT</pubDate>
            <atom:updated>2024-08-19T09:36:51.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xuYZlO9LZij7ZauBb4IOA.png" /><figcaption><a href="https://codeburst.io/get-started-with-rabbitmq-on-docker-4428d7f6e46b">Image Source</a></figcaption></figure><p>Özellikle yüksek trafik alan sistemlerde birçok kullanıcı operasyonu için asenkron bir yapıya ihtiyaç duyarız. Burada bizlere bu asenkron yapıyı sağlayan araçlardan biri de RabbitMQ’dur.</p><p>RabbitMQ oluşturduğunuz kanallar aracılığıyla kendisine gelen mesajları bir sıraya koyar ve bu sırayı Worker ya da Thread ile arka planda uygulamaya başlar. Burada eğer JavaScript tabanlı bir geliştirme yapıyorsanız şayet arka planda çalıştıracağı workerlar ile birlikte asenkron bir şekilde mesaj kuyruğunu tamamlamaya çalışır.</p><h3>Neden Asenkron?</h3><p>Geliştirmiş olduğunuz API içerisinde kayıt olan kullanıcılara bir hoşgeldiniz maili göndereceğinizi düşünün. Bu tarz bir sistemde tabii ki doğrudan nodemailer gibi bir kütüphane ile mail gönderim işleminizi tamamlayabilirsiniz. Ancak burada dikkat edilmesi gereken husus eğer mail gönderim işleminiz tamamlanmazsa ya da aynı anda birden fazla kayıt olma işlemi gerçekleşirse gibi sistemin uç noktalarıdır. İşte bu tarz uç noktalar için genellikle sistemin çalışmasını bozmayacak ama arka planda da mail işlemine devam edecek bir yapıya ihtiyaç duyarız.</p><h3>Neden RabbitMQ?</h3><p>RabbitMQ’nun sunduğu birçok avantajdan bazıları aşağıdaki gibidir. Bunca avantaj sunuyor ve gönül rahatlığıyla Docker üzerinde kendi sunucunuzda da çalıştırabiliyorken neden ekstra bütün yapıyı kendimiz yazmak zorunda kalalım ki :))</p><ul><li>Çoklu platform desteği,</li><li>Yüksek performans,</li><li>Entegrasyon kolaylığı,</li><li>Ölçeklenebilirlik</li></ul><h3>RabbitMQ Anahtarları</h3><h3>Broker</h3><p>Producer, mesajları üreten ve bu mesajları broker’a gönderen uygulama veya bileşendir. Producer, genellikle bir uygulamanın bir parçasıdır ve belirli bir olay gerçekleştiğinde mesajı oluşturur ve broker’a gönderir. Producer, birden fazla mesaj üretebilir ve bu mesajları farklı kuyruğa yönlendirebilir.</p><ul><li><strong>Örnek:</strong> Bir e-ticaret sitesinde bir sipariş oluşturulduğunda, sipariş detaylarını içeren bir mesaj, producer tarafından üretilir ve RabbitMQ’ya gönderilir. Bu mesaj daha sonra ilgili kuyruğa yerleştirilir.</li></ul><h3><strong>Producer</strong></h3><p>Producer, mesajları üreten ve bu mesajları broker’a gönderen uygulama veya bileşendir. Producer, genellikle bir uygulamanın bir parçasıdır ve belirli bir olay gerçekleştiğinde mesajı oluşturur ve broker’a gönderir. Producer, birden fazla mesaj üretebilir ve bu mesajları farklı kuyruğa yönlendirebilir.</p><ul><li><strong>Örnek:</strong> Bir e-ticaret sitesinde bir sipariş oluşturulduğunda, sipariş detaylarını içeren bir mesaj, producer tarafından üretilir ve RabbitMQ’ya gönderilir. Bu mesaj daha sonra ilgili kuyruğa yerleştirilir.</li></ul><h3><strong>Consumer</strong></h3><p>Consumer, broker tarafından gönderilen mesajları alan ve bu mesajları işleyen uygulama veya bileşendir. Consumer, belirli bir kuyruğa abone olur ve kuyrukta mesaj olduğu sürece bu mesajları alıp işler. Consumer genellikle mesajı aldıktan sonra bir işlem gerçekleştirir (örneğin, veri tabanına kaydetme, e-posta gönderme, vb.).</p><ul><li><strong>Örnek:</strong> Bir tüketici, RabbitMQ’dan bir sipariş mesajı alır ve bu mesajdaki bilgileri kullanarak stok güncellemesi yapar veya müşteriye sipariş onayı gönderir.</li></ul><h3><strong>Exchange</strong></h3><p>Exchange, mesajların broker içinde nasıl yönlendirileceğini belirleyen bir yapıdır. Exchange, gelen mesajları alır ve belirli kurallara göre mesajları ilgili kuyruklara yönlendirir. Exchange türleri arasında direct, topic, fanout, ve headers gibi farklı yönlendirme stratejileri bulunur.</p><ul><li><strong>Örnek:</strong> Bir direct exchange, routing key (yönlendirme anahtarı) kullanarak mesajları belirli bir kuyruğa yönlendirir. Eğer producer, “order_queue” adlı bir routing key ile mesaj gönderirse, bu mesaj yalnızca “order_queue” isimli kuyruğa yönlendirilir.</li></ul><h3><strong>Queue</strong></h3><p>Queue (kuyruk), mesajların depolandığı ve tüketicilerin (consumers) bu mesajları alıp işlemek için beklediği bir yapıdır. Her kuyruk bir veya daha fazla mesajı saklayabilir ve bu mesajlar tüketici tarafından işlenene kadar kuyrukta bekler. Kuyruklar genellikle FIFO (First In, First Out) prensibine göre çalışır, yani ilk gelen mesaj ilk işlenir.</p><ul><li><strong>Örnek:</strong> “order_queue” isimli bir kuyruk, tüm yeni sipariş mesajlarını alır ve bu siparişler sırasıyla tüketiciler tarafından işlenir.</li></ul><h3><strong>Routing Key</strong></h3><p>Routing key, mesajların belirli bir kuyruğa yönlendirilmesi için kullanılan bir etikettir. Producer, bir mesaj gönderirken mesajın hangi kuyruğa gitmesi gerektiğini belirlemek için routing key kullanır. Exchange, bu routing key’e göre mesajı uygun kuyruğa yönlendirir.</p><ul><li><strong>Örnek:</strong> Eğer bir sipariş mesajı “order_queue” routing key ile gönderilirse, exchange bu mesajı “order_queue” isimli kuyruğa yönlendirir.</li></ul><h3>QUEUE Türleri</h3><h3><strong>Durable Queue</strong></h3><p>Durable Queue, adından da anlaşılacağı gibi dayanıklı bir kuyruktur. Bu tür bir kuyruk, RabbitMQ sunucusu yeniden başlatılsa bile varlığını korur. Mesajlar kuyrukta kalır ve sunucu yeniden çalıştığında, mesajlar kaldığı yerden işlenmeye devam eder. Bu kuyruk türü, mesajların kaybolmaması gereken senaryolarda kullanılır.</p><p><strong>Özellikler:</strong></p><p>• <strong>Dayanıklılık:</strong> Kuyruk, sunucu yeniden başlatılsa bile korunur.</p><p>• <strong>Kullanım Alanı:</strong> Finansal işlemler, sipariş yönetim sistemleri gibi kritik verilerin kaybolmaması gereken durumlar.</p><ul><li><strong>Not:</strong> Bir kuyruğu durable yapmak için durable parametresi true olarak ayarlanır. Ancak, sadece kuyruğun dayanıklı olması yeterli değildir; aynı zamanda üretilen mesajların da kalıcı olması için persistent olarak işaretlenmesi gerekir.</li></ul><h3><strong>Exclusive Queue</strong></h3><p>Exclusive Queue, yalnızca kuyruk oluşturulduğu bağlantıya özel bir kuyruktur. Bu tür bir kuyruk, sadece onu oluşturan bağlantı tarafından erişilebilir. Bağlantı kapandığında, kuyruk otomatik olarak silinir. Exclusive Queue genellikle kısa ömürlü ve tek bir kullanıcıya özel işlemler için kullanılır.</p><p><strong>Özellikler:</strong></p><p>• <strong>Özel Kullanım:</strong> Kuyruk, sadece onu oluşturan bağlantı tarafından kullanılabilir.</p><p>• <strong>Otomatik Silme:</strong> Bağlantı kapandığında, kuyruk otomatik olarak silinir.</p><p>• <strong>Kullanım Alanı:</strong> Tek seferlik görevler, geçici oturumlar veya özel görevler için uygun bir yapıdır.</p><ul><li><strong>Not:</strong> Exclusive Queue, diğer bağlantılar tarafından erişilemez ve aynı isimde başka bir kuyruk oluşturulamaz.</li></ul><h3><strong>Auto-Delete Queue</strong></h3><p>Auto-Delete Queue, en az bir tüketici (consumer) bağlıyken kullanılabilen bir kuyruktur. Ancak, kuyrukta bağlı olan son tüketici ayrıldıktan ve kuyruktaki son mesaj işlendiğinde kuyruk otomatik olarak silinir. Bu tür kuyruklar, kısa ömürlü mesajlaşma senaryolarında tercih edilir.</p><p><strong>Özellikler:</strong></p><p>• <strong>Otomatik Silme:</strong> Son tüketici kuyruktan ayrıldığında ve kuyruk boşaldığında otomatik olarak silinir.</p><p>• <strong>Kullanım Alanı:</strong> Geçici iş süreçleri, tek seferlik görevler veya hızlıca sonuçlanacak mesajlaşmalar için uygundur.</p><ul><li><strong>Not:</strong> Kuyruğun otomatik olarak silinmesi, sistem kaynaklarının verimli kullanılmasına yardımcı olur, ancak mesajların silinme riski olduğundan kritik veriler için uygun değildir.</li></ul><h3>Docker Compose ile RabbitMQ</h3><p>Aşağıdaki örnekte verildiği gibi bir compose ile RabbitMQ’yu önce Docker ortamında kuruyoruz. Bu compose’da:</p><ul><li>Önce image ile rabbitmq sürümünü indiriyoruz,</li><li>Ardından compose dosyamızın oluşturacağı container adını belirliyoruz,</li><li>Ardından AMQP ve yönetim paneli için portlarımızı belirtiyoruz,</li><li>Herhangi bir SSL kurulumu yapacaksanız volumes altında bu sertifika dizinini eklemeniz gerekmektedir,</li><li>Ardından yönetim paneli için değişkenleri oluşturuyoruz,</li><li>Son olarak network ve restart politikasını belirleyip compose’u sonlandırıyoruz.</li></ul><pre>rabbitmq:<br>  image: rabbitmq:3.10-rc-management-alpine<br>  container_name: rabbitmq<br>  ports:<br>    - &quot;5672:5672&quot; # AMQP protocol port<br>    - &quot;15672:15672&quot; # HTTP management UI<br>  environment:<br>    RABBITMQ_DEFAULT_USER: root<br>    RABBITMQ_DEFAULT_PASS: rootpass<br>  networks:<br>    - bridge-network<br>  restart: unless-stopped</pre><p>Artık <a href="http://localhost:15672/">http://localhost:15672</a> ile yönetim paneline erişebilir geliştireceğiniz back end servisinde de 5672 portu ile RabbitMQ ile bağlantı kurabilirsiniz.</p><h3>NodeJS ile Kayıt Maili Gönderme</h3><p>Öncelikle RabbitMQ için bir listener oluşturmamız gerekiyor. Bu listener’ın amacı back end servisi çalışırken gelen mesajları dinleyerek bunları RabbitMQ’ya yönlendirmek.</p><pre>const amqp = require(&#39;amqplib/callback_api&#39;);<br>const nodemailer = require(&#39;nodemailer&#39;);<br>const generateWelcomeEmailContent = require(&quot;../emailContent/generateWelcomeEmailContent&quot;);<br><br>const startQueueListener = () =&gt; {<br>    const transporter = nodemailer.createTransport({<br>        host: process.env.SMTP_HOST,<br>        port: process.env.SMTP_PORT,<br>        secure: false,<br>        auth: {<br>            user: process.env.SMTP_USER,<br>            pass: process.env.SMTP_PASS<br>        }<br>    });<br><br>    amqp.connect(&#39;amqp://root:rootpass@localhost:5672&#39;, (error0, connection) =&gt; {<br>        if (error0) {<br>            throw error0;<br>        }<br>        connection.createChannel((error1, channel) =&gt; {<br>            if (error1) {<br>                throw error1;<br>            }<br><br>            const queues = [&#39;welcome_emails&#39;, &#39;alert_emails&#39;];<br><br>            queues.forEach(queue =&gt; {<br>                channel.assertQueue(queue, {<br>                    durable: false<br>                });<br><br>                console.log(&quot; [*] Waiting for messages in %s. To exit press CTRL+C&quot;, queue);<br><br>                channel.consume(queue, (msg) =&gt; {<br>                    const userInfo = JSON.parse(msg.content.toString());<br>                    const mailOptions = {<br>                        from: process.env.SMTP_USER,<br>                        to: userInfo.email,<br>                        subject: &#39;&#39;,<br>                        html: &#39;&#39;,<br>                    };<br><br>                    if (userInfo.type === &#39;welcomeMail&#39;) {<br>                        mailOptions.subject = `Sn. ${userInfo.name} Hoşgeldiniz`;<br>                        mailOptions.html = generateWelcomeEmailContent();<br>                    } else if (userInfo.type === &#39;alertMail&#39;) {<br>                        mailOptions.subject = &#39;Important System Alert&#39;;<br>                        mailOptions.text = `Dear user,\n\nThis is an important system alert.\n\nBest regards,\nThe Team`;<br>                    }<br><br>                    transporter.sendMail(mailOptions, (error, info) =&gt; {<br>                        if (error) {<br>                            console.log(error);<br>                        } else {<br>                            console.log(&#39;Email sent: &#39; + info.response);<br>                        }<br>                    });<br>                }, {<br>                    noAck: true<br>                });<br>            });<br>        });<br>    });<br>};<br><br>module.exports = startQueueListener;</pre><p>• <strong>amqp modülü:</strong> RabbitMQ ile iletişim kurmak için amqplib kütüphanesinin callback_api sürümünü kullanıyoruz. Bu modül, RabbitMQ’ya bağlanmamızı, kuyrukları oluşturup dinlememizi ve mesajları işlememizi sağlar.</p><p>• <strong>nodemailer modülü:</strong> E-posta göndermek için kullanılan popüler bir Node.js kütüphanesidir. SMTP üzerinden e-posta göndermeyi sağlar.</p><p>• <strong>generateWelcomeEmailContent fonksiyonu:</strong> E-posta içeriği oluşturan bir yardımcı fonksiyondur. Hoş geldiniz e-postası için HTML formatında içerik üretir.</p><p>• <strong>transporter:</strong> SMTP sunucusuna bağlanmak ve e-posta göndermek için kullanılan nodemailer nesnesidir.<br> • <strong>SMTP yapılandırması: </strong>Bu yapılandırmada SMTP sunucusu bilgileri, bağlantı noktası ve kimlik doğrulama bilgileri .env dosyasından alınmaktadır. process.env.SMTP_HOST, process.env.SMTP_PORT, process.env.SMTP_USER, process.env.SMTP_PASS gibi değişkenler bu dosyadan okunur.<br> • <strong>amqp.connect fonksiyonu:</strong> RabbitMQ’ya bağlanmak için kullanılır. Bu örnekte RabbitMQ sunucusuna amqp://root:rootpass@localhost:5672 URL’siyle bağlanılıyor.<br> • <strong>Hata kontrolü:</strong> Eğer bağlantı sırasında bir hata oluşursa (error0), hata fırlatılarak süreç durdurulur.<br> • <strong>createChannel fonksiyonu:</strong> RabbitMQ’da bir kanal oluşturur. Bu kanal üzerinden kuyruklar ile iletişim kurulur. Eğer kanal oluşturulurken bir hata oluşursa (error1), hata fırlatılır.<br> • <strong>Kuyruklar:</strong> Bu örnekte iki kuyruk dinleniyor: welcome_emails ve alert_emails.<br> • <strong>assertQueue:</strong> Bu fonksiyon, belirtilen kuyruğun var olup olmadığını kontrol eder; yoksa yeni bir kuyruk oluşturur. Bu kuyruklar durable: false parametresiyle tanımlanmıştır, yani RabbitMQ sunucusu yeniden başlatıldığında bu kuyruklar silinecektir.<br> • <strong>consume: </strong>Bu fonksiyon, belirtilen kuyruktan mesajları alır ve işleme başlar. Her bir mesaj için msg nesnesi ile bir callback fonksiyonu çalıştırılır.<br> • <strong>Mesaj içeriği: </strong>Gelen mesaj msg.content.toString() ile string’e dönüştürülür ve JSON formatında parse edilerek userInfo nesnesine atanır. Bu nesne, e-posta gönderimi için gereken bilgileri içerir.<br> • <strong>E-posta türüne göre içerik:</strong> userInfo.type değerine göre gönderilecek e-postanın konusu (subject) ve içeriği (html veya text) belirlenir.<br> • <strong>welcomeMail:</strong> Hoş geldiniz e-postası gönderilir. Konu ve içerik, generateWelcomeEmailContent() fonksiyonu kullanılarak oluşturulur.<br> • <strong>alertMail: </strong>Sistem uyarı e-postası gönderilir.<br> • <strong>E-posta gönderimi:</strong> transporter.sendMail fonksiyonu ile e-posta gönderilir. Gönderim sırasında hata oluşursa bu hata konsola yazdırılır; başarılı olursa, gönderilen e-postanın bilgisi konsola loglanır.<br> • <strong>noAck:</strong> true: Bu ayar, mesajların alındı onayı (acknowledgement) olmadan otomatik olarak işlenmesini sağlar. Bu, mesajın işlenmesinden sonra RabbitMQ’nun mesajı otomatik olarak kuyruktan silmesini sağlar. Eğer noAck false olsaydı, mesajın başarılı bir şekilde işlendiğine dair bir onay verilmesi gerekirdi.<br> • <strong>module.exports:</strong> startQueueListener fonksiyonunu dışa aktararak başka dosyalardan bu fonksiyonun çağrılmasını sağlar. Bu sayede, uygulamanın başka bir kısmından startQueueListener fonksiyonu başlatılabilir ve RabbitMQ kuyrukları dinlemeye başlayabilir.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd1d66289cb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[STM32 Yazılımını OTA ile Güncelleme]]></title>
            <link>https://medium.com/@hidirektor/stm32-yaz%C4%B1l%C4%B1m%C4%B1n%C4%B1-ota-ile-g%C3%BCncelleme-39a7ab405b46?source=rss-896b10891d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/39a7ab405b46</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[embedded]]></category>
            <category><![CDATA[restful]]></category>
            <category><![CDATA[overtheair]]></category>
            <dc:creator><![CDATA[Halil İbrahim Direktör]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 23:02:45 GMT</pubDate>
            <atom:updated>2023-12-30T23:05:02.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*b2NA-msPYXA8-rWo0tah7g.png" /><figcaption>Image Source:<a href="https://intellias.com/how-to-realize-ota-updates-for-connected-cars/"> intellias</a></figcaption></figure><p>Gömülü sistem yazılımlarında belki de en kritik aşama geliştirilen yazılımın uzaktan güncellenebiliyor olmasıdır. Geliştirdiğiniz yazılımı müşterinize sunduktan sonra yazılımsal bir iyileştirme, bug fix ya da genel optimizasyon süreçleri için yazılımın barındığı kartı ya da ürünü müşteriden geri almak hem abesle iştigal edecektir hem de lojistik maliyetleriyle birlikte daha bir sürü masraf kalemi çıkaracaktır.</p><h3>Bir Yazılımı Nasıl Güncelleriz ?</h3><p>Bu soruya geliştirilen yazılımın hangi platformda çalıştığıyla ilgili farklı farklı cevaplar verilebilir. Örneğin sunucu tarafında çalışan servis yazılımını Docker üzerinden güncelleyebilirsiniz. Ya da bir masaüstü programını güncelleyecekseniz programın çalışma süreciyle birlikte hareket eden bir ön program geliştirerek program dosyalarını güncelleyebilirsiniz.</p><p>Ancak bugün konumuz doğrudan mikro işlemci içerisine yüklediğiniz yazılımı kolay ve hızlı bir şekilde nasıl güncelleyeceğimizdir. Bunun için öncelikle OTA/FOTA, IAP ve CRC tanımlarını inceleyeceğiz.</p><h3>OTA/FOTA (Over The Air)</h3><p>Güncelleme yayınlama yöntemlerinden biridir. Over The Air ya da Firmware Over The Air yani herhangi bir fiziksel temas olmaksızın yazılımın güncellenmesi anlamına gelmektedir.</p><h3>IAP (In Application Programming)</h3><p>In Application Programming anlamına gelen bu kavram aslında standart yazılım geliştirme sürecinizi temsil eder. Gömülü sistemin istediğiniz şekilde çalışması için yaptığınız programlamada ki tüm fonksiyon ve yazdığınız kodlar IAP olarak adlandırılır.</p><h3>CRC (Cyclic Redundancy Check)</h3><p>CRC olarak adlandırdığımız hata kontrol algoritması aslında bir dosyanın belli başlı hesaplama yöntemleriyle sayısal bir veri haline getirilerek orijinal dosya ve alınan dosya tarafında iki kere kontrol edilerek dosyanın sorunsuz gelip gelmediğinin kontrol edilmesidir.</p><h3>ESP8266 ile Güncelleme</h3><p>ESP8266 ile IAP tarzında bir güncelleme kontrol yazılımı yapmadan önce bu işlemi nasıl yapacağımızı planlayalım:</p><p>1- .bin dosyasını endpoint halinde servis eden Node.js scriptin yazılması,<br>2- ESP8266 ile WiFi bağlantısının kurulması,<br>3- Gerekli endpointi kullanarak güncel .bin dosyası için request atılması,<br>4- Request sonrası dosya bütünlüğünün kontrol edilmesi,<br>5- Dosya bütünlüğünde sorun yoksa güncel .bin dosyasının sisteme yazılması.</p><h3>Güncelleme Dosyası için Servis Yazımı</h3><p>Güncelleme dosyasını yayınlayacağımız servis için seçtiğimiz dil ve kütüphane JavaScript ve Node.js’tir. Burada JavaScript tercihimin sebebi hızlı geliştirilebilir olmasıdır. Bunun yanında Java ve Spring Boot kullanarakta servis yazabilirsiniz.</p><ul><li>Yazacağınız servis son kullanıcıya çıkacaksa muhakkak Authentication ve Authorization önlemlerini de düşünün. Aksi takdirde güvenlik açıklarıyla boğuşmak zorunda kalabilirsiniz.</li></ul><p>Hadi gelin servis tarafını yazalım:</p><p>Öncelikle kullanacağımız kütüphaneleri:</p><pre>const express = require(&#39;express&#39;);<br>const fs = require(&#39;fs&#39;);<br>const crypto = require(&#39;crypto&#39;);</pre><p>Express sunucusu ve port için gerekli değişkenleri oluşturalım:</p><pre>const app = express();<br>const port = 3000;</pre><p>Oluşturacağımız endpointin request tipini belirtelim ve response olarak dönecek .bin dosyasıyla birlikte bu dosyasının CRC değerini header aracılığıyla isteği atan client’a gönderelim.</p><pre>app.get(&#39;/firmware&#39;, (req, res) =&gt; {<br>  const firmwarePath = &#39;firmwares/firmware.bin&#39;;<br>  const firmware = fs.readFileSync(firmwarePath);<br><br>  const crc = calculateCRC32(firmware);<br>  res.setHeader(&#39;x-crc32&#39;, crc.toString(16));<br><br>  res.sendFile(firmwarePath);<br>});</pre><p>Burada seçtiğimiz CRC algoritması CRC-32&#39;dir.</p><p>CRC32 hesaplaması için gerekli calculateCRC32 fonksiyonunu yazalım:</p><pre>function calculateCRC32(buffer) {<br>  const crc = crypto.createHash(&#39;crc32&#39;);<br>  crc.update(buffer);<br>  return crc.digest(&#39;hex&#39;);<br>}</pre><p>Artık Express server’ı başlatabiliriz:</p><pre>app.listen(port, () =&gt; {<br>  console.log(`Server is running at http://localhost:${port}`);<br>});</pre><h3>ESP8266 ile WiFi Bağlantısı Kurma</h3><p>Bunun için öncelikle ESP8266&#39;nın gerekli seri bağlantılarını yapmanız gerekiyor. STM32&#39;de bu bağlantı için PA9 ve PA10 pinleri standart olarak kullanılmaktadır.</p><p>Öncelikle bağladığınız ESP8266&#39;yı sıfırlamamız gerekiyor bunun için:</p><pre>sprintf(bufferTX, &quot;AT+RESTORE\r\n&quot;);<br> HAL_UART_Transmit_IT(huart1, (uint8_t*) bufferTX, strlen(bufferTX));<br> HAL_Delay(1000);</pre><p>Ardından ESP8266&#39;yı resetliyoruz:</p><pre>sprintf(bufferTX, &quot;AT+RST\r\n&quot;);<br> HAL_UART_Transmit_IT(huart1, (uint8_t*) bufferTX, strlen(bufferTX));<br> HAL_Delay(1000);</pre><p>ESP8266&#39;da herhangi bir sorun olup olmadığını anlamak için AT komutunu gönderiyoruz:</p><pre>sprintf(bufferTX, &quot;AT\r\n&quot;);<br> HAL_UART_Transmit_IT(huart1, (uint8_t*) bufferTX, strlen(bufferTX));<br> HAL_Delay(2000);</pre><p>ESP8266&#39;nın bir Client olduğunu belirtmek için gerekli AT komutunu gönderiyoruz:</p><pre>sprintf(bufferTX, &quot;AT+CWMODE=1\r\n&quot;);<br> HAL_UART_Transmit_IT(huart1, (uint8_t*) bufferTX, strlen(bufferTX));<br> HAL_Delay(2000);</pre><p>Artık bağlanmak istediğimiz wifi ismi ve şifresiyle CWJAP komutunu kullanarak wifi bağlantısını sağlıyoruz:</p><pre>char str[100];<br> strcpy(str, &quot;AT+CWJAP=\&quot;&quot;);<br> strcat(str, wifiSS);<br> strcat(str, &quot;\&quot;,\&quot;&quot;);<br> strcat(str, wifiPA);<br> strcat(str, &quot;\&quot;\r\n&quot;);<br> sprintf(bufferTX, &quot;%s&quot;, str);<br> HAL_UART_Transmit_IT(huart1, (uint8_t*) bufferTX, strlen(bufferTX));<br> HAL_Delay(2000);</pre><h3>Güncel .bin Dosyasını Sunucudan Çekme</h3><p>Bu işlem için öncelikle calculateCRC32 fonksiyonunu yazalım:</p><pre>uint32_t calculateCRC32(uint8_t *buffer, size_t length) {<br>  uint32_t crc = 0xFFFFFFFF;<br><br>  for (size_t i = 0; i &lt; length; i++)<br>  {<br>    crc ^= buffer[i];<br><br>    for (size_t j = 0; j &lt; 8; j++)<br>    {<br>      crc = (crc &amp; 1) ? (crc &gt;&gt; 1) ^ 0xEDB88320UL : crc &gt;&gt; 1;<br>    }<br>  }<br><br>  return crc ^ 0xFFFFFFFF;<br>}</pre><p>Bu fonksiyon gelen her bir veri byte’ı için XOR işlemi yaparak LSB’si yani en az anlamlı biti 1 ise sağa kaydırma 0 ise sola kaydırma yapar tabii ki bu kaydırma işlemleri fonksiyon içinde tanımlanan crc değişkeni için yapılır.</p><p>CRC hesaplamamız hazır olduğuna göre artık sunucumuza istek atabiliriz. Öncelikle sunucudan IP almakla başlayalım:</p><pre>char command[100];<br>    sprintf(command, &quot;AT+CIPSTART=\&quot;TCP\&quot;,\&quot;%s\&quot;,%d&quot;, &quot;127.0.0.1&quot;, 3000);<br>    HAL_UART_Transmit(huart1, (uint8_t *)command, strlen(command), HAL_MAX_DELAY);</pre><p>Sunucudan IP aldığımıza göre artık GET isteğimizi atabiliriz:</p><pre>char getRequest[200];<br>    sprintf(getRequest, &quot;GET /firmware HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n&quot;, &quot;127.0.0.1&quot;);<br>    sprintf(command, &quot;AT+CIPSEND=%d&quot;, strlen(getRequest));<br>    HAL_UART_Transmit(huart1, (uint8_t *)command, strlen(command), HAL_MAX_DELAY);<br>    HAL_UART_Transmit(huart1, (uint8_t *)getRequest, strlen(getRequest), HAL_MAX_DELAY);</pre><p>Sunucudan gelen yanıtı düzgün almak için bir bekleme süresi ekleyelim:</p><pre>HAL_Delay(5000);</pre><p>Sunucudan gelen yanıtı işleyelim:</p><pre>char receivedData[1024];<br>    memset(receivedData, 0, sizeof(receivedData)); // Null-terminate the buffer<br>    HAL_UART_Receive(huart1, (uint8_t *)receivedData, sizeof(receivedData) - 1, HAL_MAX_DELAY);<br><br>    HAL_Delay(500);</pre><p>Bağlantıyı kapatalım:</p><pre>char closeCommand[] = &quot;AT+CIPCLOSE&quot;;<br>    HAL_UART_Transmit(huart1, (uint8_t *)closeCommand, strlen(closeCommand), HAL_MAX_DELAY);</pre><p>Artık gelen dosyanın CRC’sini sunucudakiyle kontrol edip STM32&#39;nin başlangıç adresine gelen veriyi yazabiliriz:</p><pre>uint32_t calculatedCRC = calculateCRC32((uint8_t *)receivedData, strlen(receivedData));<br><br>    char *headerStart = strstr(receivedData, &quot;x-crc32: &quot;);<br>    if (headerStart != NULL) {<br>      uint32_t serverCRC = strtol(headerStart + 9, NULL, 16); // 9: strlen(&quot;x-crc32: &quot;)<br><br>      // CRC değerlerini karşılaştır<br>      if (calculatedCRC == serverCRC) {<br>        HAL_FLASH_Unlock();<br>        uint32_t address = 0x08000000; // Başlangıç adresi<br><br>        // Program belleğe yaz<br>        for (uint32_t i = 0; i &lt; strlen(receivedData); i += 4) {<br>          uint32_t data;<br>          memcpy(&amp;data, &amp;receivedData[i], sizeof(uint32_t));<br><br>          // Program belleğe yaz<br>          HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, address, data);<br><br>          // Bellek adresini güncelle<br>          address += 4;<br>        }<br><br>        HAL_FLASH_Lock();<br>        HAL_Delay(200);<br>        NVIC_SystemReset();<br>      } else {<br>        lcd_print(1, 1, &quot;  DOSYA HATASI  &quot;);<br>      }<br>    }</pre><p>Tüm bu süreçte şunlara değinmemiz gerekiyor:<br>1- HAL_UART_Transmit_IT ve HAL_UART_Transmit arasındaki fark HAL_UART_Transmit fonksiyonunda istek sürecinin bitmesi beklenirken HAL_UART_Transmit_IT fonksiyonunda işlem başlatılır ve bittiğinde bittiğine dair bir interrupt (kesme) gönderilir.<br>2- Kullandığınız STM32 mikroişlemci modeline göre başlangıç adresiniz değişebilir.<br>3- uint32_t serverCRC = strtol(headerStart + 9, NULL, 16); bu kod satırının amacı headerda CRC’den önce yazan gereksiz karakterleri silmektir.<br>4- Bu kodları farklı bir headerda kullanmak istiyorsanı fonksiyonunuz parametre olarak UART_HandleTypeDef *huart1 değişkenini almalıdır.<br>5- Daha kapsamlı ve daha performanslı bir yazılım güncelleme sistemi için bootloader ile güncelleme konularına göz atabilirsiniz :)</p><p>Böylece artık sorunsuz olarak yazılım güncellemelerinizi kendi sunucunuz ve kendi altyapınızla gerçekleştirebilirsiniz. Tabii ki canlıya çıkmadan önce gerekli Authentication, Authorization ve API limitlendirmelerini eklemeyi unutmayın :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39a7ab405b46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending HTTP Requests on Embedded Systems based USART]]></title>
            <link>https://medium.com/@hidirektor/sending-http-requests-on-embedded-systems-based-usart-f1b39dfebbb6?source=rss-896b10891d87------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1b39dfebbb6</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[embedded]]></category>
            <dc:creator><![CDATA[Halil İbrahim Direktör]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 10:17:30 GMT</pubDate>
            <atom:updated>2023-11-15T10:17:30.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*Bg1Nv0wcB3yStR3sAxIiOg.png" /></figure><p>As an embedded systems enthusiast, in this article, I will discuss one of the most crucial communication protocols for an embedded system to establish a secure connection with the outside world: HTTP Request protocols.</p><p>Why Do We Need an HTTP Request Protocol?</p><p>Under normal circumstances, if you are developing a project for DIY or hobby purposes, you may not directly need HTTP protocols. This is because closed systems of this kind do not require a direct channel to establish a connection with the outside world. However, if your project involves connecting with the outside world, either receiving data from or sending data to the external environment, you will need to use HTTP protocols. This can be better illustrated with an example:</p><p>Imagine a scenario where you purchase a robot vacuum cleaner, regardless of the brand. To connect this robot vacuum cleaner to your Wi-Fi, you first download the manufacturer’s mobile application. Then, you connect the product directly to your home network through the mobile application. After this process, the robot vacuum cleaner sends its internal data to the manufacturer’s servers. If you want to check the data, you can connect to the manufacturer’s server through the mobile application and retrieve the necessary information.</p><p>This process is essentially carried out using HTTP protocols. In fact, when you connect this robot vacuum cleaner to your home network, you have enabled the manufacturer to make requests to the robot vacuum cleaner’s endpoints.</p><p>What Are These HTTP Protocols?</p><p>There are four types of HTTP protocols that can be used during data exchange with the server. These are, in order: GET, POST, PUT, and DELETE protocols. These protocols are also referred to as CRUD operations: C(reate) R(ead) U(pdate) D(elete).</p><p>With explanations that you can find in many sources, these protocols are defined as follows:</p><ul><li>GET: Used for retrieving data from the server.</li><li>POST: Used for sending and receiving data from the server. This protocol includes file-type data.</li><li>PUT: Used for updating data on the server.</li><li>DELETE: Used for deleting data on the server.</li></ul><p>Let’s add some additional information to these existing details:</p><ul><li>You don’t necessarily have to use the GET request only for retrieving data. In necessary situations, you can use this protocol to send data to the server for a single endpoint and numerous parameters.</li><li>You can use the POST request seamlessly for all file operations and make all your requests in JSON and multi-part binary (file) formats with this protocol.</li><li>Especially in your file deletion processes, using the DELETE request will make your work much more practical.</li></ul><p>Usage of HTTP Requests in Embedded Systems: To use HTTP protocols in an embedded system, it is necessary to first explain USART, TCP, UDP, and additionally, the concept of Ethernet.</p><ul><li>USART, or in other words, UART is a serial data transmission protocol. When transmitting data:</li><li>It operates asynchronously and cannot interact with any other unit at any time.</li><li>Baudrate is critically important, and for smooth data transfer, both the receiver and the transmitter must operate at the same baudrate.</li><li>TCP is a connection-based protocol. It performs error control and returns whether the connection is established.</li><li>UDP does not care whether the connection is established or not. It sends the given data directly to the specified address without performing any error control.</li><li>lwIP is a TCP/IP stack library designed for embedded systems. You can directly download and use it from any embedded system IDE.</li></ul><p>Sending HTTP Requests:</p><p>The code lines you will need to send an HTTP request are as simple and straightforward as the following. The code below sends the specified request to the given address, transmitting the data via USART to the Wi-Fi or Internet module you have connected in a serial manner.</p><pre>char reqArr[200];<br>sprintf(reqArr,<br>   &quot;GET /api/user/userID?userName=%s HTTP/1.0\r\nHost: %s\r\n\r\n&quot;, userID, userName);<br>int len = strlen(reqArr);<br><br>HAL_UART_Transmit_IT(huart1, (uint8_t*) local_txA, strlen(local_txA));<br>HAL_Delay(6000);</pre><ul><li>The use of IT in HAL_UART_Transmit_IT here is because we want the delay time to be MAX_Delay.</li></ul><p>You have reached the end of my first writing, and I thank you for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1b39dfebbb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>