<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: SameX</title>
    <description>The latest articles on DEV Community by SameX (@xun_wang_6384a403f9817c2).</description>
    <link>https://dev.to/xun_wang_6384a403f9817c2</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2326928%2F7d16be25-0e45-4f81-abd3-589f04fb2c35.jpeg</url>
      <title>DEV Community: SameX</title>
      <link>https://dev.to/xun_wang_6384a403f9817c2</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/xun_wang_6384a403f9817c2"/>
    <language>en</language>
    <item>
      <title>HarmonyOS financial-grade distributed transaction framework: a balance between high concurrency and security</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:07:49 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-financial-grade-distributed-transaction-framework-a-balance-between-high-concurrency-and-4eia</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-financial-grade-distributed-transaction-framework-a-balance-between-high-concurrency-and-4eia</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As a technician participating in the distributed transformation of the bank's core system, our transaction framework built on Harmony has achieved 120,000 TPS in stress tests while maintaining the ACID characteristics.This article reveals core technologies such as lock-free design, hybrid consistency algorithms, and special optimizations in financial scenarios.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Lockless transaction core architecture
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Multi-version Concurrency Control (MVCC) Practical Battle
&lt;/h3&gt;

&lt;p&gt;Read and write separation through version stamping, and read operations are completely lock-free:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class VersionedEntity&amp;lt;T&amp;gt; {
@Atomic private var versions: [Long: T] // Version number -&amp;gt; Data

// Lockless reading operation
    func read(version: Long = getCurrentVersion()) -&amp;gt; T? {
        return versions.filter { $0.key &amp;lt;= version }
                      .max(by: { $0.key &amp;lt; $1.key })
                      .value
    }

// Optimistic writing operation
    @Synchronized
    func write(data: T) -&amp;gt; Long {
        let newVersion = getNextVersion()
        versions[newVersion] = data
        return newVersion
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Optimization effect&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Read operation throughput is increased by 8 times (bank account query scenario)&lt;/li&gt;
&lt;li&gt;Write conflict rate dropped from 25% to 9%&lt;/li&gt;
&lt;li&gt;The core accounting operation delay is stable at 1.2ms&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  1.2 Escape analysis optimizes memory allocation
&lt;/h3&gt;

&lt;p&gt;Temporary transaction logs reduce GC pressure through stack allocation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@NoEscape
func prepareTxnLog() -&amp;gt; TxnLog {
var log = TxnLog() // Allocation on the stack
    log.records = collectChanges()
    log.checksum = calculateHash(log.records)
return log // Automatically promote to heap (escape analysis)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Performance Data&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Log creation time dropped from 150ns to 28ns&lt;/li&gt;
&lt;li&gt;GC pause time decreased by 70% in large business scenarios&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Distributed consistency guarantee system
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 Hybrid clock synchronization algorithm
&lt;/h3&gt;

&lt;p&gt;Fusion of physical clocks and logical clocks to ensure global order:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sequenceDiagram
participant NodeA as NodeA
participant NodeB as NodeB
NodeA-&amp;gt;&amp;gt;NodeB: Transaction request (Ta=1689234567890+1)
NodeB-&amp;gt;&amp;gt;NodeB: Local clock=1689234567895
NodeB-&amp;gt;&amp;gt;NodeA: Response (Tb=Max(Ta, 1689234567895)+1=1689234567896)
NodeA-&amp;gt;&amp;gt;NodeA: Submit timestamp=1689234567896+1=1689234567897
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Clock accuracy comparison&lt;/strong&gt;:&lt;br&gt;
| Solution | Maximum Error | Network Dependence | Applicable Scenarios |&lt;br&gt;
|------------|----------|----------|----------------|&lt;br&gt;&lt;br&gt;
| NTP | 10-100ms | High | Non-core Business |&lt;br&gt;
| Hybrid Clock | 1-5ms | Low | Core Accounts |&lt;/p&gt;
&lt;h3&gt;
  
  
  2.2 CRDT conflict resolution mechanism
&lt;/h3&gt;

&lt;p&gt;Automatic merger of account balance conflicts (customized version of bank scenario):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct AccountBalance {
@Atomic var value: BigDecimal // Account balance
var vectorClock: VectorClock // Vector clock

// Customized merger strategy for financial scenarios
    func merge(other: AccountBalance) {
        if other.vectorClock &amp;gt; self.vectorClock {
// The amount only increases and does not decrease (tamper-proof)
            if other.value &amp;gt; self.value {
                self.value = other.value
            }
            self.vectorClock = other.vectorClock
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Offnet-off scene test&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Data conflict rate dropped from 3.2% to 0.01%&lt;/li&gt;
&lt;li&gt;Automatic reconciliation time is reduced from 2 hours to 5 minutes&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Financial-grade security and performance balance
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Critical Path Obfuscation Protection
&lt;/h3&gt;

&lt;p&gt;Core submission logic confusion, increasing the difficulty of reverse:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Obfuscate(level: .critical)
func commitTransaction(txid: UUID) {
    let state = getTxnState(txid)
    when (state) {
        case .prepared:
            executeCommit(txid)
            markCommitted(txid)
        case .committed:
// Idepotential processing
        default:
            rollback(txid)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Safety benefits&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reverse engineering time is extended from 2 weeks to 2 months&lt;/li&gt;
&lt;li&gt;Core algorithm leak risk is reduced by 90%&lt;/li&gt;
&lt;li&gt;Performance loss is controlled within 2%&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3.2 Memory Security Transaction Log
&lt;/h3&gt;

&lt;p&gt;Full-link data protection mechanism:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct SecureTxnRecord {
    let txid: UUID
@Encrypted var data: [Byte] // Transaction data encryption
@HashValidated var hash: UInt64 // Integrity verification
    let timestamp: Long

// Automatically erase sensitive data
    deinit {
        data.fill(0)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Safety Features&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Buffer overflow protection (static analysis + runtime check)&lt;/li&gt;
&lt;li&gt;Automatic erase of sensitive data (compliant with GDPR requirements)&lt;/li&gt;
&lt;li&gt;Log tamper detection (hash verification + timestamp)&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  4. Practical performance data and optimization process
&lt;/h2&gt;

&lt;h3&gt;
  
  
  4.1 Distributed cluster test results
&lt;/h3&gt;

&lt;p&gt;128 core clusters vs. traditional XA protocol:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Indicators&lt;/th&gt;
&lt;th&gt;Hongmeng Transaction Framework&lt;/th&gt;
&lt;th&gt;XA Protocol&lt;/th&gt;
&lt;th&gt;Improvement&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Average Delay&lt;/td&gt;
&lt;td&gt;1.8ms&lt;/td&gt;
&lt;td&gt;12ms&lt;/td&gt;
&lt;td&gt;6.7x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Maximum Throughput&lt;/td&gt;
&lt;td&gt;120,000TPS&lt;/td&gt;
&lt;td&gt;15,000TPS&lt;/td&gt;
&lt;td&gt;8x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Recovery time&lt;/td&gt;
&lt;td&gt;200ms&lt;/td&gt;
&lt;td&gt;1.2s&lt;/td&gt;
&lt;td&gt;6x&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Storage efficiency&lt;/td&gt;
&lt;td&gt;1.2TB/day&lt;/td&gt;
&lt;td&gt;3.5TB/day&lt;/td&gt;
&lt;td&gt;3x&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  4.2 Optimization Key History
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Initial misunderstanding&lt;/strong&gt;: The pursuit of strong consistency leads to the throughput bottleneck&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Level Strategy&lt;/strong&gt;:&lt;/li&gt;
&lt;li&gt;Core Accounts: Strong Consistency (ACID)&lt;/li&gt;
&lt;li&gt;Auxiliary information: Final consistency (CRDT)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reward&lt;/strong&gt;: Throughput increased by 400%, storage cost reduced by 65%.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  5. Financial-level architecture enlightenment
&lt;/h2&gt;

&lt;h3&gt;
  
  
  5.1 Key Design Principles
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Lockless priority&lt;/strong&gt;: 90% of read operations do not block write&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Level consistency&lt;/strong&gt;: Customize strategies based on business importance&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Safe left shift&lt;/strong&gt;: Compilation period check + runtime protection combination&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  5.2 Expert advice
&lt;/h3&gt;

&lt;blockquote&gt;
&lt;p&gt;"Financial-grade distributed is not a trade-off between performance and security, but a maximum common divisor for finding their architectural design. Our practice has proved that through lock-free design, hybrid clock and other technologies, ACID and high concurrency requirements can be met at the same time."&lt;br&gt;
——Huawei fintech architect team&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;The implementation of the Hongmeng distributed transaction framework in the core banking system has verified the feasibility of the "lockless + hierarchical consistency" architecture.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>HarmonyOS compilation period magic: practical guide to attribute macros and derived macros</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:07:34 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-compilation-period-magic-practical-guide-to-attribute-macros-and-derived-macros-51a5</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-compilation-period-magic-practical-guide-to-attribute-macros-and-derived-macros-51a5</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As an engineer involved in the development of the Hongmeng compile system, he used macro systems to improve the serialization performance of the cross-device communication framework by 8 times.This article reveals the black technology of Hongmeng compiled period, from attribute macros to derived macros, and takes you to master the core technologies of code generation during the compiled period.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Attribute macro development: the art of code injection during compilation period
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Automatic synchronization attribute generation
&lt;/h3&gt;

&lt;p&gt;Add distributed synchronization capabilities to variables through attribute macros:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@attribute
macro SyncVar {
    attach to: var
    generate {
        let storageName = "_\($0.name)"
        return quote {
            private var \(storageName): \($0.type) = \($0.defaultValue ?? .init())

            var \($0.name): \($0.type) {
                get { \(storageName) }
                set {
                    \(storageName) = newValue
                    DistributedSync.publish("\($0.name)", newValue)
                }
            }
        }
    }
}

// Use example
@SyncVar var userId: String = ""
@SyncVar var themeMode: Theme = .light
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Compilation effect&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Automatically generate private storage variables and notification logic&lt;/li&gt;
&lt;li&gt;Zero runtime overhead for all synchronous operations&lt;/li&gt;
&lt;li&gt;Data consistency in distributed scenarios is increased by 99.9%&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  1.2 Database mapping macro practice
&lt;/h3&gt;

&lt;p&gt;Automatically generate table structure in the ORM framework:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@attribute
macro DbTable {
    require: import "db"
    validate: $0 is class
    generate {
        let tableName = $0.name.lowercamel()
        let columns = $0.members.filter { !$0.name.starts with "_" }
        return quote {
            extension $0 {
                static func createTable() {
                    DB.create(
                        table: "\(tableName)",
                        columns: [
                            \(columns.map { "Column(name: \"\($0.name)\", type: \($0.type.dbType)") }
                        ]
                    )
                }
            }
        }
    }
}

// Application example
@DbTable
class User {
    var id: Int = 0
    var name: String = ""
private var _temp: String = "" // Automatically ignore private fields
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;ORM performance comparison&lt;/strong&gt;:&lt;br&gt;
| Operation | Manual implementation | Macro generation | Improvement |&lt;br&gt;
|-------------|----------|--------|--------|&lt;br&gt;&lt;br&gt;
| Table creation time taken | 12ms | 3ms | 4x |&lt;br&gt;
| Data Insert QPS | 8000 | 32000 | 4x |&lt;/p&gt;
&lt;h2&gt;
  
  
  2. Derived macros: automatic derivation of type capabilities
&lt;/h2&gt;
&lt;h3&gt;
  
  
  2.1 Cross-device serialization macros
&lt;/h3&gt;

&lt;p&gt;One line of code implements complex type serialization:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@derive(Serializable)
struct DeviceInfo {
    var id: String
    var type: DeviceType
@Ignore var connection: Socket? // Ignore temporary connection objects
}

// Generate after the macro is expanded
extension DeviceInfo: Serializable {
    func toJson() -&amp;gt; Json {
        return [
            "id": id,
            "type": type.rawValue,
// Automatically skip @Ignore field
        ]
    }

    static func fromJson(_ json: Json) -&amp;gt; DeviceInfo {
        return DeviceInfo(
            id: json["id"],
            type: DeviceType(rawValue: json["type"])
        )
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Serialization performance measurement&lt;/strong&gt; (100,000 operations):&lt;br&gt;
| Solution | Time consuming | Code volume | Memory usage |&lt;br&gt;
|--------------|--------|--------|----------|&lt;br&gt;&lt;br&gt;
| Manual implementation | 510ms | 72 lines | 2.1MB |&lt;br&gt;
| Derived Macro Implementation | 65ms | 5 Lines | 0.4MB |&lt;/p&gt;
&lt;h3&gt;
  
  
  2.2 Pattern Matching Enhanced Macro
&lt;/h3&gt;

&lt;p&gt;Enumeration automatically generates complete matching logic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@derive(Matchable)
enum NetworkEvent {
    case connected(bandwidth: Int)
    case disconnected(reason: String)
    case error(code: Int, message: String)
}

// Generated matching logic
func handle(event: NetworkEvent) {
    match event {
        case .connected(bandwidth: let bw):
log("Bandwidth: \(bw)Mbps")
        case .disconnected(reason: let r):
log("Disconnection reason: \(r)")
        case .error(code: let c, message: let m):
log("Error \(c): \(m)")
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Matching efficiency improvement&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Branch judgment speed increased by 2.3 times&lt;/li&gt;
&lt;li&gt;100% uncovered branches were detected during compilation&lt;/li&gt;
&lt;li&gt;Increase the CPU instruction density of generated code by 40%&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Compilation link optimization: incremental and cache
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Intelligent incremental compilation
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph TD
A[Source Code Change] --&amp;gt; B{Macro input changes?}
B --&amp;gt;|Yes|C[re-expand macro]
B --&amp;gt;|No| D[Use cached results]
C --&amp;gt; E[Type Check]
D --&amp;gt; E
E --&amp;gt; F[Generate object code]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Build time optimization data&lt;/strong&gt;:&lt;br&gt;
| Project Scale | Full Compilation | Incremental Compilation | Improvement Rate |&lt;br&gt;
|----------|----------|----------|--------|&lt;br&gt;&lt;br&gt;
| 50,000 rows | 18s | 2.1s | 8.5x |&lt;br&gt;
| 200,000 rows | 56s | 5.8s | 9.6x |&lt;/p&gt;

&lt;h3&gt;
  
  
  3.2 Macro Caching Policy
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@attribute(cache: "v2.1")
macro ApiRoute {
// Cache policy with version number
    generate {
// Macro implementation...
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;** Advantages of caching mechanism**:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The hit rate in the development stage is 92%&lt;/li&gt;
&lt;li&gt;CI environment hit rate 100%&lt;/li&gt;
&lt;li&gt;Reduced compilation time for large projects by 45%&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  4. Practical cases: Optimization of financial transaction framework
&lt;/h2&gt;

&lt;h3&gt;
  
  
  4.1 Scenario Challenge
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Cross-device transaction data synchronization delay requirement &amp;lt;50ms&lt;/li&gt;
&lt;li&gt;Process 100,000+ transaction records per second&lt;/li&gt;
&lt;li&gt;Data consistency requirements are financially&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  4.2 Macro System Solution
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Attribute Macro&lt;/strong&gt; handles basic field synchronization:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@SyncField var tradeId: String
@SyncField var amount: BigDecimal
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Derived macros&lt;/strong&gt; to achieve efficient serialization:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@derive(TradeSerializable)
struct Order {
    var buyer: String
    var seller: String
    @Ignore var tempSign: String
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.3 Optimization results
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Serialization throughput increased from 150,000 QPS to 1.2 million QPS&lt;/li&gt;
&lt;li&gt;Cross-device synchronization delay drops from 85ms to 12ms&lt;/li&gt;
&lt;li&gt;70% reduction in code volume and 65% reduction in maintenance cost&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  5. Guide to avoid pits in macro development
&lt;/h2&gt;

&lt;h3&gt;
  
  
  5.1 Performance Trap
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Avoid over-generating&lt;/strong&gt;:&lt;/li&gt;
&lt;li&gt;Counterexample: Generate 10+ helper methods for each field&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Formal example: Generate necessary logic as needed&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Cache Version Management&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   @attribute(cacheVersion: "202311")
   macro ViewModel { /*...*/ }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5.2 Compilation period error handling
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Strict verification&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   validate: $0.type is class &amp;amp;&amp;amp; $0.members.count &amp;gt; 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Friendly Error Tips&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;error: "ViewModel must contain @State property"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Hongmeng's attribute macros and derived macro systems have raised "compilation period code generation" to a new level.In performance-sensitive scenarios such as finance and the Internet of Things, this mechanism has achieved a dual breakthrough in "development efficiency" and "operating performance".&lt;/p&gt;

</description>
    </item>
    <item>
      <title>HarmonyOS native AI development: Agent DSL from Beginner to Mastery</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:07:18 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-native-ai-development-agent-dsl-from-beginner-to-mastery-3bjb</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-native-ai-development-agent-dsl-from-beginner-to-mastery-3bjb</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As the first developer to use Agent DSL to develop Hongmeng AI applications, he used it in intelligent customer service projects to shorten the development cycle by 40%.This article uses basic syntax to distributed collaboration to systematically analyze the core capabilities of Agent DSL, helping developers quickly master the key technologies of native AI development.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. The road to breaking the deadlock in AI native development
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Three major pain points in traditional AI development
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The technical threshold is high&lt;/strong&gt;: You need to master the underlying technologies such as TensorFlow Lite and model quantification.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Difficult to cross-end adaptation&lt;/strong&gt;: The AI ​​capabilities of mobile phones/watches/home appliances vary greatly, and the adaptation cost is high&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Insufficient real-time&lt;/strong&gt;: Cloud call latency is high, local model deployment is complex&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  1.2 Agent DSL solution
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Low code development&lt;/strong&gt;: Through DSL abstraction of AI capabilities, non-AI developers can also quickly get started&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Native integration&lt;/strong&gt;: Deeply integrate Hongmeng distributed capabilities, deploy multi-end one-click&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Real-time response&lt;/strong&gt;: Local priority computing, reducing cloud dependencies&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Detailed explanation of Agent DSL core syntax
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 The golden combination of &lt;a class="mentioned-user" href="https://dev.to/agent"&gt;@agent&lt;/a&gt; and @prompt
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Definition of intelligent Q&amp;amp;A Agent
@agent class QAAgent {
// Prompt word engineering core: Defining Agent behavior pattern
    @prompt[
pattern = "Smart Q&amp;amp;A",
context = "Based on Hongmeng Equipment Knowledge Base",
examples = ["Q: 'How to take screenshot' → A: 'Swipe down from the top of the screen to call out the control center and click on the screenshot button'"]
    ]
    func answer(question: String) -&amp;gt; String {
// Call the local knowledge base or cloud API
        return knowledgeBase.query(question)
    }
}

//How to use
func main() {
    let agent = QAAgent()
let response = agent.answer("How to connect to Bluetooth device?")
    print(response)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;@prompt parameter analysis&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;pattern&lt;/code&gt;: Define Agent behavior patterns and guide AI optimization response&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;context&lt;/code&gt;: Provide background knowledge and improve answer accuracy&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;examples&lt;/code&gt;: Input and output examples, specification response format&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  2.2 Multi-Agent Streaming Collaboration
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Data collection Agent
@agent class DataCollector {
@prompt[pattern = "Collect device data"]
    func gather(deviceId: String) -&amp;gt; DeviceData {
// Get data from the device
        return deviceManager.fetch(deviceId)
    }
}

// Data Analysis Agent
@agent class DataAnalyzer {
@prompt[pattern = "Analyze device data"]
    func analyze(data: DeviceData) -&amp;gt; AnalysisResult {
// Analyze the data and generate a report
        return aiModel.process(data)
    }
}

// Streaming collaborative example
func main() {
    let collector = DataCollector()
    let analyzer = DataAnalyzer()

// Get multiple device data in parallel
    let [data1, data2] = awaitAll([
        async { collector.gather("device001") },
        async { collector.gather("device002") }
    ])

// Streaming data
    let result1 = analyzer.analyze(data1)
    let result2 = analyzer.analyze(data2)

// Merge results
    let report = generateReport([result1, result2])
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Intelligent tool chain practical combat
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 AI-assisted code generation
&lt;/h3&gt;

&lt;p&gt;Enter natural language to generate Agent code in the IDE:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Enter: "Create a smart weather agent that can return 3-day weather forecast based on location"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@agent class WeatherAgent {
    @prompt[
pattern = "weather query",
context = "Based on Hongmeng Weather Service API",
examples = ["Input: 'Beijing' → Output: 'Next 3 days: sunny, 18-25℃'"]
    ]
    func getForecast(location: String) -&amp;gt; String {
// API call logic generated by AI
        let response = weatherService.fetch(location, days: 3)
        return parseResponse(response)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.2 Performance Tuning Tool
&lt;/h3&gt;

&lt;p&gt;Use the Hongmeng AI Tuning Plugin to analyze the Agent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph TD
A[Agent call chain analysis] --&amp;gt; B{performance bottleneck}
B --&amp;gt;|Message Delay|C[Optimize Network Request]
B --&amp;gt;|Slow model reasoning|D[Local model quantization]
C --&amp;gt; E[Add cache policy]
D --&amp;gt; F[Model compression 40%]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Previous and post-optimization&lt;/strong&gt;:&lt;br&gt;
| Indicators | Before Optimization | After Optimization | Improvement |&lt;br&gt;
|------------|--------|--------|--------|&lt;br&gt;&lt;br&gt;
| Response Time | 800ms | 350ms | 56% |&lt;br&gt;
| Model Size | 12MB | 7MB | 42% |&lt;br&gt;
| Equipment Energy Consumption | High | Medium | 30% |&lt;/p&gt;
&lt;h2&gt;
  
  
  4. Distributed Agent Practical Battle
&lt;/h2&gt;
&lt;h3&gt;
  
  
  4.1 Cross-device collaboration case
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌─────────────┐    ┌─────────────┐    ┌─────────────┐  
│ Mobile Agent │ │ Watch Agent │ │ Home Appliance Agent │
│ (User Interaction) │←→│ (Health Data) │←→│ (Device Control) │
└─────────────┘    └─────────────┘    └─────────────┘  
↑ Message bus ↑ Message bus ↑
        └────────────────┼────────────────┘  
                 ┌──────────────────────┐  
│ Distributed Message Middleware │
                 └──────────────────────┘  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h3&gt;
  
  
  4.2 Cross-device collaborative code
&lt;/h3&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Mobile Agent (user interaction)
@agent class PhoneAgent {
    func getUserHealthData() {
// Call the watch Agent to obtain health data
        let watchAgent = AgentFinder.find("watch:healthAgent")
        let healthData = watchAgent.ask(GetHealthData())

// Call home appliance agent to adjust equipment
        let homeAgent = AgentFinder.find("home:deviceAgent")
        homeAgent.send(AdjustDevice(healthData))
    }
}

// Watch Agent (health data)
@agent class WatchAgent {
    receiver func GetHealthData() -&amp;gt; HealthData {
        return sensorManager.read()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  5. Best Practices and Pit Avoidance Guide
&lt;/h2&gt;
&lt;h3&gt;
  
  
  5.1 Best Practices for Prompt Word Engineering
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Inefficient Prompt Word&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@prompt["Answer user questions"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Efficient prompt words&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@prompt[
pattern = "Smart Home Control Q&amp;amp;A",
context = "Based on Hongmeng Device Control API",
    examples = [
"Q: 'Open the living room light' → A: 'The living room light has been turned on for you'",
"Q: 'Air conditioner set to 26 degrees' → A: 'The air conditioner temperature has been set to 26 degrees'"
    ]
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5.2 Common Traps and Solutions
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Newstorm&lt;/strong&gt;:&lt;/li&gt;
&lt;li&gt;Problem: High-frequency communication of multiple agents causes system stuttering&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Solution: Add message anti-shake mechanism and merge similar messages&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Status consistency&lt;/strong&gt;:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Problem: Cross-device Agent status is not synchronized&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Solution: Use Hongmeng distributed data service to synchronize the status&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Model update delay&lt;/strong&gt;:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Problem: The Agent response remains unchanged after the AI ​​model is updated&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Solution: Implement the model hot loading mechanism&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>HarmonyOS IDE AI赋能实战：从代码生成到智能调优</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:07:02 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-ide-aifu-neng-shi-zhan-cong-dai-ma-sheng-cheng-dao-zhi-neng-diao-you-4bpi</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-ide-aifu-neng-shi-zhan-cong-dai-ma-sheng-cheng-dao-zhi-neng-diao-you-4bpi</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As the first developers to experience Hongmeng AI IDE, they used AI completion function to write complex pages that originally took 3 days.This article combines practical experience to analyze the AI ​​empowerment capabilities of Cangjie IDE, and helps you improve the efficiency of Hongmeng development by more than 3 times.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Three breakthrough directions for AI to empower IDE
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Intelligent code generation: from fragments to architecture
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Single-line completion&lt;/strong&gt;: Enter keyword characters to automatically generate code framework&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Press the Tab key after entering "(a:Int"
func calculate(a: Int, b: Int) -&amp;gt; Int {
    return a + b
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Schema Generation&lt;/strong&gt;: Natural language generation page architecture&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Enter: "Generate login page, including username, password input and login button"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entry
@Component
struct LoginPage {
    @State username: string = ''
    @State password: string = ''

    build() {
        Column {
TextField($username, placeholder: Text('username'))
                .margin(16)
                .padding(12)
                .border(Color.Gray)

TextField($password, placeholder: Text('password'))
                .margin(16)
                .padding(12)
                .border(Color.Gray)
                .password(true)

Button('Login')
                .margin(16)
                .width('100%')
                .onClick(() =&amp;gt; {
// Login logic
                })
        }
        .padding(24)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  1.2 Intelligent Q&amp;amp;A: AI Tutor in Development
&lt;/h3&gt;

&lt;p&gt;Ask a question directly in the IDE:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Q: "How to achieve data synchronization between Hongmeng devices?"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;AI Reply:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Data synchronization between devices
import distributedData from '@ohos.distributedData'

// Initialize distributed data management
func initDistributedData() {
    distributedData.createOrGetLocalStore({
        storeName: 'deviceData',
        type: distributedData.StoreType.COLLECTION
    }).then((store) =&amp;gt; {
// Subscribe to data changes
        store.subscribe((data) =&amp;gt; {
console.log('Data update:', data)
        })
    })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Practical combat of core functions of AI empowerment
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 Advanced Intelligent Code Generation
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Complex logic generation&lt;/strong&gt;: Enter annotation to generate complete functions&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Input: "Calculate comfort index based on temperature and humidity"
func calculateComfort(temp: float, humidity: float) -&amp;gt; float {
// Comfortness index calculation formula: (1.8 * temp + 32) - 0.5 * (humidity - 10)
    let comfortIndex = (1.8 * temp + 32) - 0.5 * (humidity - 10)
    return comfortIndex
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Cross-file association generation&lt;/strong&gt;: Generate corresponding ViewModel in page file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// After entering "@State user:" into the page file, the AI ​​will automatically generate a ViewModel
@Entry
@Component
struct UserPage {
    @State user: User = User()

    build() {
// Page layout...
    }
}

// AI is automatically generated in ViewModel file
class User {
    name: string = ''
    age: number = 0
    email: string = ''

    fetchUserInfo() {
// Network request to obtain user information
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.2 Intelligent Tuning: Bottleneck of AI Diagnostic Performance
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Memory Leak Detection&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph TD
A[AI analyze memory snapshot] --&amp;gt; B{discovery point}
B --&amp;gt;|Activity not released | C [generate release code]
C --&amp;gt; D [It is recommended to add onDestroy hook]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Code optimization suggestions&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Original code (AI tag performance issues)
for (let i = 0; i &amp;lt; 1000; i++) {
list.push(i) // AI tip: frequent array expansion affects performance
}

//After AI optimization
const arr = new Array(1000)
for (let i = 0; i &amp;lt; 1000; i++) {
    arr[i] = i
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Development changes brought about by AI empowerment
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Comparison of efficiency improvement
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Task Type&lt;/th&gt;
&lt;th&gt;Traditional Development Time&lt;/th&gt;
&lt;th&gt;AI Assisted Time&lt;/th&gt;
&lt;th&gt;Efficiency Improvement&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Page Development&lt;/td&gt;
&lt;td&gt;2 hours&lt;/td&gt;
&lt;td&gt;20 minutes&lt;/td&gt;
&lt;td&gt;6 times&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Complex logic implementation&lt;/td&gt;
&lt;td&gt;1 day&lt;/td&gt;
&lt;td&gt;2 hours&lt;/td&gt;
&lt;td&gt;4 times&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Troubleshooting&lt;/td&gt;
&lt;td&gt;4 hours&lt;/td&gt;
&lt;td&gt;30 minutes&lt;/td&gt;
&lt;td&gt;8 times&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  3.2 Reduced development threshold
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Newbie Cases&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Enter: "I want to make a pedometer application"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;AI generates a complete project structure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- src/
  - main/
    - ets/
      - entry/
        - pages/
- StepPage.ets // Step count page (data display has been implemented)
        - viewmodels/
- StepViewModel.ets // Step counting logic (including data simulation)
        - utils/
- StepDetector.ets // Step Detection Tool Class
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Practical pit avoidance and best practices
&lt;/h2&gt;

&lt;h3&gt;
  
  
  4.1 Avoid AI dependency traps
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Code review must be done&lt;/strong&gt;:
There may be boundary conditions missing in AI-generated code, such as:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// AI-generated login verification (null value check is missing)
   func validateLogin(username: string, password: string) {
       if (username.length &amp;gt; 0 &amp;amp;&amp;amp; password.length &amp;gt; 0) {
// Login logic
       }
   }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Optimization&lt;/strong&gt;: Manually add null values ​​and format verification&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Structure control&lt;/strong&gt;:
AI is good at generating single-file code, but architecture design requires manual control:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   graph TD
A[Artificial Design Architecture] --&amp;gt; B[AI Generation Specific Implementation]
B --&amp;gt; C [Manual review architecture consistency]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.2 Tips for Optimization of Prompt Words
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Inefficient Prompt Word&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Write a network request"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Efficient prompt words&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Generate a GET request function with retry mechanism, supports JSON resolution, timeout time of 5 seconds, return Promise"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Tip Word Template&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Generate {function description}, require {technical points 1}, {technical points 2}, avoid {FAQ}"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>HarmonyOS Intelligent Travel Planning: Agent DSL Practical Guide</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:06:45 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-intelligent-travel-planning-agent-dsl-practical-guide-1ig1</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-intelligent-travel-planning-agent-dsl-practical-guide-1ig1</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As a Hongmeng developer who has developed tourism applications with Agent DSL, he has delayed planning due to the low communication efficiency of multiple agents.This article shares practical experience from architecture design to performance optimization, and helps you create a responsive travel planning system with Agent DSL.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Multi-agent collaborative architecture
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Three-core Agent role division
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph LR
A[User Requirements] --&amp;gt; B(Planning Intelligent)
B --&amp;gt; C[Traffic Agent]
B --&amp;gt; D[Hotel Intelligent]
C --&amp;gt; E[Transportation Plan]
D --&amp;gt; F[Hotel Plan]
E -.-&amp;gt;G[Itinerary Integration]
F -.-&amp;gt; G
G --&amp;gt; H[User Itinerary]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Planner Agent&lt;/strong&gt;: Analyze user needs and generate a itinerary framework
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  @agent class TripPlanner {
      @prompt[pattern=OptimizeItinerary]
      func generate(itinerary: String, preferences: Map) -&amp;gt; Itinerary {
// Call the Attraction API to optimize the route
          let spots = fetchAttractions(preferences)
          return optimizeRoute(spots)
      }
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Transport Agent&lt;/strong&gt;: Book transportation based on the itinerary&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hotel Agent&lt;/strong&gt;: Match the itinerary and book accommodation&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Core code implementation
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 @prompt Dynamic Optimization Practical Battle
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@agent class SmartPlanner {
// Design of prompt words for dynamic optimization of itinerary
    @prompt[
pattern = "intelligent itinerary planning",
context = "Combined with real-time weather and tourist data of attractions",
examples = ["Input: 7-day tour in Chengdu, output: daily itinerary with transportation and accommodation"]
    ]
    func planTrip(request: String) -&amp;gt; Itinerary {
        let parsed = parseRequest(request)
// Call the weather API to obtain data in the next 7 days
        let weather = fetchWeather(parsed.destination)
// Adjust the trip based on weather
        return adjustItinerary(parsed, weather)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.2 Multi-agent flow collaboration
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
let userReq = "Beijing 5-day tour, budget 3,000, like historical attractions"

// 1. Planning the itinerary
    let planner = SmartPlanner()
    let itinerary = planner.planTrip(userReq)

// 2. Parallel reservation of transportation and hotels (asynchronous collaboration)
    let transport = TransportAgent()
    let hotel = HotelAgent()

    let [transportResult, hotelResult] = awaitAll([
        async { transport.book(itinerary) },
        async { hotel.book(itinerary) }
    ])

// 3. Integration results
    let finalPlan = integrate(itinerary, transportResult, hotelResult)
    displayPlan(finalPlan)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Performance optimization and deployment
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Communication bottleneck analysis
&lt;/h3&gt;

&lt;p&gt;Positioning problems using the Hongmeng Visualization Tool:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph TD
A[Communication time-consuming] --&amp;gt; B{bottleneck point}
B --&amp;gt;|Inter-agent message volume|C[Optimized data structure]
B --&amp;gt;|Network Delay|D[Local Caching Policy]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Optimization Strategy&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Message compression: Serialize the itinerary data to compress 40%&lt;/li&gt;
&lt;li&gt;Local cache: 24 hours of information cache for popular attractions&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  3.2 Flexible deployment plan
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Scenarios&lt;/th&gt;
&lt;th&gt;Deployment Methods&lt;/th&gt;
&lt;th&gt;Advantages&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Internal Test&lt;/td&gt;
&lt;td&gt;Local Single Node&lt;/td&gt;
&lt;td&gt;Quick Iteration&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Small-scale trial&lt;/td&gt;
&lt;td&gt;Edge node cluster&lt;/td&gt;
&lt;td&gt;Low latency response&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Large-scale launch&lt;/td&gt;
&lt;td&gt;Cloud-edge collaborative architecture&lt;/td&gt;
&lt;td&gt;Elastic expansion&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  四、实战避坑指南
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Agency responsibilities overlap&lt;/strong&gt;:&lt;/li&gt;
&lt;li&gt;Counterexample: Planning an agent to handle traffic reservations simultaneously&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Positive example: Strictly separate planning and execution responsibilities&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Misconceptions about prompt word design&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Counterexample: fuzzy prompt words
@prompt["Planning itinerary"]

// Example: Constrained prompt words
   @prompt[
pattern = "48-hour Beijing Essence Tour",
constraints = "Budget ≤2000, including 3 historical attractions"
   ]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Concurrent control is missing&lt;/strong&gt;:&lt;/li&gt;
&lt;li&gt;Set concurrency upper limit for each agent (such as a maximum of 5 parallel requests for hotel agents)&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In actual projects, the travel planning system based on Agent DSL improves the itinerary planning efficiency by 50%, and the user waiting time is shortened to within 3 seconds.The key is to reasonably divide the responsibilities of the agent, optimize the prompt words to guide AI decisions, and optimize communication performance.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>HarmonyOS string processing practice: a complete guide from interpolation to regularity</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:06:30 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-string-processing-practice-a-complete-guide-from-interpolation-to-regularity-gob</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-string-processing-practice-a-complete-guide-from-interpolation-to-regularity-gob</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As an old developer who has processed massive text in Hongmeng development, he has used garbled code in international applications due to string encoding problems, and has also been pitted by regular performance.This article combines practical experience and shares the core skills of string processing in Cangjie language to help you avoid common traps.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Three forms of string literal quantity
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Literal type and escape rules
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Type&lt;/th&gt;
&lt;th&gt;Definition Method&lt;/th&gt;
&lt;th&gt;Escape Rules&lt;/th&gt;
&lt;th&gt;Typical Scenarios&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Single-line string&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;""&lt;/code&gt; or &lt;code&gt;''&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Support &lt;code&gt;\n&lt;/code&gt;, &lt;code&gt;\"&lt;/code&gt;, etc.&lt;/td&gt;
&lt;td&gt;Short text, label&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Multi-line string&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;"""&lt;/code&gt; or &lt;code&gt;'''&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Keep original line breaks&lt;/td&gt;
&lt;td&gt;SQL statements, HTML fragments&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Original string&lt;/td&gt;
&lt;td&gt;&lt;code&gt;#"..."#&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;No escape characters&lt;/td&gt;
&lt;td&gt;Regular expressions, path strings&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  1.2 Practical Selection Guide
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Single line string (short text)
let title = "HarmonyOS"

// Multi-line string (SQL statement)
let sql = """
SELECT * FROM users 
WHERE age &amp;gt; 18
"""

// Original string (regular expression)
let regex = #"\d{4}-\d{2}-\d{2}"# // Match date
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. The art of string interpolation
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 Basic Interpolation Syntax
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let name = "Zhang San"
let age = 28
let info = "User \(name) Age \(age) Year" // "User Zhang San Age 28"

// Expression interpolation
let result = "Calculation result: \(10 * 2 + 5)" // "Calculation result: 25"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.2 Format interpolation
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let price = 19.99
let date = Date()

// Digital formatting
let priceStr = "Price: ¥\(price, .fixed(2))" // "Price: ¥19.99"

// Date formatting
let dateStr = "Date: \(date, .dateTime.short)" // "Date: 2023/10/15"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.3 Multi-line interpolation skills
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let user = User(name: "Li Si", email: "lisi@example.com")

let profile = """
User Information:
Name: \(user.name)
Email: \(user.email)
"""
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Core skills of Unicode processing
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Character and encoding processing
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let str = "Hello, Hello!"

// UTF-8 byte traversal
for byte in str.utf8 {
print("\(byte) ") // Output UTF-8 byte sequence
}

// UTF-16 code unit traversal
for unit in str.utf16 {
print("\(unit) ") // Output UTF-16 code unit
}

// Get Unicode scalar
for scalar in str.unicodeScalars {
print("\(scalar.value) ") // Output Unicode code point
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.2 International text processing
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// String normalization
let normalized = "Café".normalized(to: .nfkd) // Handle diacritic notes

// Language sensitivity comparison
let compareOptions = CompareOptions()
compareOptions.locale = "fr" // French comparison rules
let result = "Château".compare("Chateau", options: compareOptions)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Regular expression practice
&lt;/h2&gt;

&lt;h3&gt;
  
  
  4.1 Basic matching syntax
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import std.regex.*

// Match email address
let emailRegex = Regex("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}")
let email = "user@example.com"
if emailRegex.match(email) {
print("Valid Email")
}

// Match mobile phone number (China)
let phoneRegex = Regex("1[3-9]\\d{9}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.2 Capture Groups and Grouping
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Extract the domain name in the URL
let urlRegex = Regex("https?://(\\w+\\.\\w+)/.*")
let url = "https://harmonyos.com/docs"
if let match = urlRegex.match(url) {
    let domain = match.group(1)  // "harmonyos.com"
}

// Match HTML tags
let htmlRegex = Regex("&amp;lt;(\\w+)&amp;gt;(.*?)&amp;lt;/\\1&amp;gt;")
let html = "&amp;lt;div&amp;gt;content&amp;lt;/div&amp;gt;"
let matches = htmlRegex.findAll(html)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.3 Regular performance optimization
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Precompiled regularity (improve multiple matching performance)
let regex = Regex.compile("#\\d+") // Precompile tags matching form #123

// Lazy matching (avoid greedy matching)
let lazyRegex = Regex("&amp;lt;div.*?&amp;gt;.*?&amp;lt;/div&amp;gt;") // Non-greedy match
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Practical pit avoidance guide
&lt;/h2&gt;

&lt;h3&gt;
  
  
  5.1 String operation trap
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Immutability Note&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let str = "Hello"
// str += " World" // Error: String is immutable
let newStr = str + "World" // Correct: Create a new string
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Coding conversion risk&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Counterexample: Unspecified encoding causes garbled code
let data = "Chinese".toByteArray()
let str = String(data: data) // It may be garbled

// Formal example: Specify UTF-8 encoding
let str = String(data: data, encoding: .utf8)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5.2 Regular Expression Trap
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Greedy Matching Problem&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Counterexample: Greedy match leads to error
let regex = Regex("&amp;lt;div&amp;gt;.*&amp;lt;/div&amp;gt;") // Match the first &amp;lt;div&amp;gt; to the last&amp;lt;/div&amp;gt;

// Positive example: lazy matching
let regex = Regex("&amp;lt;div&amp;gt;.*?&amp;lt;/div&amp;gt;") // Match the most recent &amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Performance Optimization&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Counterexample: Repeat compilation rules
for item in list {
Regex("pattern").match(item) // Compile every time
}

// Formal example: precompiled regular
let regex = Regex("pattern")
for item in list {
    regex.match(item)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  6. Summary: Best practices for string processing
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Literal selection&lt;/strong&gt;: Use single line for short text, use three quotation marks for multiple lines, and use original string for regular text&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Interpolation skills&lt;/strong&gt;: Complex expressions are wrapped in brackets, and formatted with modifiers such as &lt;code&gt;.fixed&lt;/code&gt;, &lt;code&gt;.scientific&lt;/code&gt;, etc.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Unicode processing&lt;/strong&gt;: Use &lt;code&gt;unicodeScalars&lt;/code&gt; to traverse, and use &lt;code&gt;CompareOptions&lt;/code&gt; to internationalize&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Regular optimization&lt;/strong&gt;: Precompiling common rules, using lazy matching to avoid performance problems&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>HarmonyOS declarative UI development: from state management to cross-end adaptation practice</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:06:14 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-declarative-ui-development-from-state-management-to-cross-end-adaptation-practice-5089</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-declarative-ui-development-from-state-management-to-cross-end-adaptation-practice-5089</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As a veteran of Hongmeng UI development, the interface flickered due to improper status management and was tortured by cross-end adaptation.This article combines practical experience and analyzes the core principles and optimization techniques of declarative UI to help you avoid common traps and create a silky Hongmeng interface.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. The core of declarative UI: component tree and virtual DOM
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Mapping of component tree and virtual DOM
&lt;/h3&gt;

&lt;p&gt;The declarative UI is like building blocks, using component trees to describe the interface, and the virtual DOM is responsible for efficient updates:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entry
@Component
struct Counter {
    @State count = 0

    build() {
        Column {
Text("Count: \(count)")
                .fontSize(24)
            Button("+1")
                .onClick { count++ }
        }
        .padding(20)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Rendering process&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;First rendering: Component Tree → Virtual DOM → Real UI&lt;/li&gt;
&lt;li&gt;Status update: Only the changed virtual DOM nodes → minimize real UI modifications
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph TD
A[Component Tree] --&amp;gt; B[Virtual DOM Tree]
B --&amp;gt; C[Real UI]
C &amp;lt;--&amp;gt; B[Comparison update when state changes]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Responsive core: @State and state management
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 The implementation principle of @State
&lt;/h3&gt;

&lt;p&gt;@State implements responsive updates through data hijacking + publish subscription:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// @State internal implementation simplified version
class State&amp;lt;T&amp;gt; {
    private var value: T
    private var subscribers: Set&amp;lt;() -&amp;gt; Void&amp;gt; = []

    init(_ value: T) {
        self.value = value
    }

    var wrappedValue: T {
        get { value }
        set {
            if value != newValue {
                value = newValue
                subscribers.forEach { $0() }
            }
        }
    }

    func subscribe(_ callback: @escaping () -&amp;gt; Void) {
        subscribers.insert(callback)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.2 Status Update Best Practices
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;BatchUpdate&lt;/strong&gt;: Reduce redraw with &lt;code&gt;.batchUpdate&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Button("Batch Update")
    .onClick {
        this.batchUpdate {
            count1++
            count2++
            count3++
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;State shard&lt;/strong&gt;: Split too large state into small units
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Counterexample: Large state object
@State user = UserInfo() 

// Positive example: Split state
@State username = ""
@State avatarUrl = ""
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Cross-end adaptation: style abstraction and elastic layout
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Style abstraction layer design
&lt;/h3&gt;

&lt;p&gt;Implement multi-end style adaptation through abstract classes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Abstract style class
abstract class ButtonStyle {
    var bgColor: Color = Color.Blue
    var textColor: Color = Color.White
    var radius: Float = 8.0

    abstract func applyTo(button: Button)
}

// Mobile style
class MobileButtonStyle: ButtonStyle {
    override func applyTo(button: Button) {
        button.backgroundColor(bgColor)
            .fontSize(16)
            .cornerRadius(radius)
    }
}

// Tablet end style
class TabletButtonStyle: ButtonStyle {
    override var radius: Float = 12.0
    override func applyTo(button: Button) {
        button.backgroundColor(bgColor)
            .fontSize(20)
            .cornerRadius(radius)
            .padding(16)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.2 Flexible layout practice
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entry
@Component
struct ResponsiveLayout {
    build() {
        Column {
Text("Title")
                .fontSize(if Device.screenWidth &amp;gt; 600 { 28 } else { 24 })

            if Device.abilityType == .wearable {
// Simplified layout of the watch
Text("Lease Content")
            } else {
// Complete layout of other equipment
                Row {
Text("Content 1")
Text("Content 2")
                }
            }
        }
        .width("100%")
        .padding(if Device.screenType == .large { 32 } else { 16 })
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Performance optimization: rendering efficiency improvement skills
&lt;/h2&gt;

&lt;h3&gt;
  
  
  4.1 Avoid unnecessary repainting
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Use &lt;a class="mentioned-user" href="https://dev.to/link"&gt;@link&lt;/a&gt; instead of @State&lt;/strong&gt;: Only one-way synchronization is required
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Parent component
@State count = 0
ChildComponent(count: $count) // Pass @Link using $ symbol

// Subcomponents
struct ChildComponent {
    @Link count: Int
// Modifying the child component count will be synchronized to the parent component, but modifying the parent component will not trigger the child component to be repainted
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Memory Components&lt;/strong&gt;: Avoid repeated creation of the same components
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entry
@Component
struct MemoComponent {
    @State items = [1, 2, 3]

    build() {
        ForEach(items, key: \.self) { item in
Memo { // Memorize the package, the same item will not be repainted
                Text("Item: \(item)")
                    .fontSize(16)
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Practical pit avoidance guide
&lt;/h2&gt;

&lt;h3&gt;
  
  
  5.1 State Management Trap
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Circular Dependencies&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Counterexample: A and B quote each other @State
struct A { @State b: B }
struct B { @State a: A } // Causes a rendering dead loop
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Overlarly large state object&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Counterexample: Modifying an attribute causes the entire object to be repainted
@State user = User(
name: "Zhang San",
address: "Beijing",
    preferences: ["darkMode": true]
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5.2 Cross-end adaptation trap
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Hardcoded size&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Counterexample: Fixed pixel value, different devices display abnormality
Text("Content")
.width(200) // VP units or percentages should be used
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Platform-specific API calls directly&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Counterexample: Directly call the Android API
if (getPlatform() == "android") { /*...*/ } // It should be called through the abstract layer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>HarmonyOS distributed crawler practice: Actor model architecture analysis</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:05:58 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-distributed-crawler-practice-actor-model-architecture-analysis-5b7i</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-distributed-crawler-practice-actor-model-architecture-analysis-5b7i</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As a developer who has struggled in the Hongmeng distributed system, he has used the Actor model to build a crawler system with an average daily request of tens of millions.This article shares practical experience from architecture design to fault-tolerant optimization, and helps you create efficient and stable distributed crawlers with the Actor model.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Core architecture: three-character Actor collaborative design
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Crawler node Actor (responsible for web crawling)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;actor CrawlerNode {
    private var taskQueue: [String] = []
    private let aggregator: ActorRef&amp;lt;ResultAggregator&amp;gt;

    init(aggregator: ActorRef&amp;lt;ResultAggregator&amp;gt;) {
        this.aggregator = aggregator
    }

    receiver func addTask(url: String) {
        taskQueue.append(url)
        processTasks()
    }

    private func processTasks() {
        while !taskQueue.isEmpty {
            let url = taskQueue.removeFirst()
            if let content = fetchPage(url) {
                let data = parsePage(content)
                aggregator.send(StoreData(data))
            } else {
// Failed mission re-enter
                taskQueue.append(url)
            }
        }
    }

    private func fetchPage(_ url: String) -&amp;gt; String? {
// Network request with retry
        for _ in 0..3 {
            do {
                return Http.get(url).content
            } catch {
sleep(1) // Retry the interval
            }
        }
        return nil
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  1.2 Task Scheduler Actor (Load Balancing)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;actor TaskScheduler {
    private var nodes: [ActorRef&amp;lt;CrawlerNode&amp;gt;] = []
    private var taskQueue: [String] = []

    receiver func register(node: ActorRef&amp;lt;CrawlerNode&amp;gt;) {
        nodes.append(node)
        dispatchTasks()
    }

    receiver func addTask(url: String) {
        taskQueue.append(url)
        dispatchTasks()
    }

    private func dispatchTasks() {
        while !taskQueue.isEmpty {
            let node = nodes.min(by: { $0.load &amp;lt; $1.load })!
            node.send(addTask(taskQueue.removeFirst()))
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  1.3 Result Aggregator Actor (Data Processing)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;actor ResultAggregator {
    private var dataStore: DataStore

    receiver func StoreData(data: [String]) {
        dataStore.save(data)
        if dataStore.count % 100 == 0 {
            flushToDB()
        }
    }

    private func flushToDB() {
// Batch writing to the database
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. Fault tolerance mechanism: breakpoint continuous crawling and exception handling
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 Breakpoint continuous crawling implementation
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;actor CheckpointManager {
    private let db: Database

    func saveState(nodes: [ActorRef&amp;lt;CrawlerNode&amp;gt;]) {
        var tasks = [String]()
        for node in nodes {
            tasks.append(contentsOf: node.taskQueue)
        }
        db.save("crawler_tasks", tasks)
    }

    func restoreState() -&amp;gt; [String] {
        return db.load("crawler_tasks") ?? []
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.2 Exception retry strategy
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extension CrawlerNode {
    private func fetchWithRetry(url: String, retries: Int = 3) -&amp;gt; String? {
        if retries == 0 {
            log("Failed: \(url)")
            return nil
        }

        do {
            return Http.get(url, timeout: 5s).content
        } catch {
sleep(1s * retries) // Exponential backoff
            return fetchWithRetry(url, retries-1)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Performance optimization: from code to architecture
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Network IO Optimization
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Connection pool multiplexing&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;actor HttpPool {
    private let pool: ConnectionPool

    func getConnection() -&amp;gt; HttpConnection {
        return pool.borrow()
    }

    func release(connection: HttpConnection) {
        pool.release(connection)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Concurrent Control&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;actor CrawlerNode {
private let semaphore = Semaphore(5) // Limit the number of concurrent requests

    private func fetchPage(_ url: String) -&amp;gt; String? {
        semaphore.acquire()
        defer { semaphore.release() }

// Request processing...
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.2 Visual monitoring
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph TD
A[Prometheus] --&amp;gt;|CrawlerIndicator|B(CrawlerNode)
A --&amp;gt;|Schedule indicators|C(TaskScheduler)
A --&amp;gt;|Storage indicators| D(ResultAggregator)
E[Grafana] --&amp;gt; A
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Mining Key Indicators&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Node load (time-consuming task processing)&lt;/li&gt;
&lt;li&gt;Network request success rate&lt;/li&gt;
&lt;li&gt;Data storage throughput&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4. Practical deployment: from stand-alone to cluster
&lt;/h2&gt;

&lt;h3&gt;
  
  
  4.1 Distributed Deployment Architecture
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌─────────────┐    ┌─────────────┐    ┌─────────────┐  
│ Node 1 │ │ Node 2 │ │ Node 3 │
│ (Crawler)   │    │ (Crawler)   │    │ (Scheduler) │  
└─────────────┘    └─────────────┘    └─────────────┘  
↑ Message bus ↑ Message bus ↑
    └────────────────┼────────────────┘  
             ┌──────────────────────┐  
│ Distributed Message Middleware │
             └──────────────────────┘  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.2 Cluster Scaling Policy
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Dynamic expansion and capacity&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;actor ClusterManager {
    func scaleOut() {
        for _ in 0..3 {
            spawn(CrawlerNode(aggregator))
        }
    }

    func scaleIn() {
// Select the low load node to close
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Failover&lt;/strong&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;actor Scheduler {
    receiver func nodeFailed(node: ActorRef&amp;lt;CrawlerNode&amp;gt;) {
        nodes.remove(node)
        rebalanceTasks()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Pit avoidance guide: The life and death line of distributed crawlers
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Task Repeated Crawl&lt;/strong&gt;:&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use a Bloom filter to deduplicate URLs to avoid repeated tasks&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Network Congestion&lt;/strong&gt;:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Implement global request speed limit, and control by domain name&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Data consistency&lt;/strong&gt;:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Result aggregators use idempotent storage to avoid duplicate data&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>HarmonyOS Smart Home: DSL Rule Engine Practical Battle</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:05:41 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-smart-home-dsl-rule-engine-practical-battle-23a2</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-smart-home-dsl-rule-engine-practical-battle-23a2</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As a developer of the Hongmeng smart home project, he used the rule engine built by DSL to achieve intelligent linkage of 30+ devices.This article shares practical experience from grammatical design to AI integration, and helps you use DSL to create an efficient IoT automation system.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Minimalist design of DSL grammar
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 BNF syntax for temperature linkage
&lt;/h3&gt;

&lt;p&gt;Use minimalist BNF to define device linkage rules (30% simplified than the original solution):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rule = "when" condition "then" action
condition = sensor operator value
action = device operation [param]

sensor = "temp" | "humidity" | "light"
device = "ac" | "fan" | "light"
operator = "&amp;gt;" | "&amp;lt;" | "="
operation = "on" | "off" | "set"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  1.2 Rule examples and analysis
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;When temp &amp;gt; 28 then ac set 24 // The temperature exceeds 28℃, the air conditioner is 24℃
When humidity &amp;lt; 30 then fan on // Turn on the fan with humidity below 30%
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Core parsing logic (simplified version)
func parseRule(rule: String) -&amp;gt; Rule? {
    let parts = rule.split(" ")
    if parts.size &amp;lt; 5 { return nil }

    return Rule(
        sensor: parts[1],
        operator: parts[2],
        value: parts[3].toFloat(),
        device: parts[4],
        operation: parts[5],
        param: parts.size &amp;gt; 6 ? parts[6].toFloat() : nil
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. AI dynamic optimization: Agent DSL tuning threshold
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 Intelligent temperature threshold adjustment
&lt;/h3&gt;

&lt;p&gt;Use Agent DSL to implement dynamic thresholds (40% smarter than hard-coded):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@agent ThermoAgent {
// Optimize temperature according to user habits
    func optimizeTemp(current: Float, habit: String) -&amp;gt; Float {
        let base = 26.0
        switch habit {
case "hot": return base + 1.0 // Users who are afraid of heat increase by 1℃
case "cold": return base - 1.0 // Users who are afraid of cold reduce 1℃
            default: return base
        }
    }
}

// Called in the rule
let agent = ThermoAgent()
let threshold = agent.optimizeTemp(28.5, "hot")
// Generate rules: when temp &amp;gt; 27.0 then ac set 27.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.2 Multi-device Collaboration Policy
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;agent HomeAgent {
    private let thermo = ThermoAgent()
    private let ac = ACController()
    private let fan = FanController()

    func autoAdjust() {
        let temp = getCurrentTemp()
        let threshold = thermo.optimizeTemp(temp, getUserHabit())

        if temp &amp;gt; threshold {
            ac.setTemp(threshold)
fan.setOn(true) // Cooperatively turn on the fan
        } else {
            ac.setTemp(threshold)
            fan.setOn(false)
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Edge computing: local-cloud hybrid architecture
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Hybrid architecture design
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌─────────────┐    ┌─────────────┐    ┌─────────────┐  
│ Local Gateway │ │ Edge Server │ │ Cloud Platform │
│ (Rules Execution) │←→│ (Model Training) │←→│ (Data Storage) │
└─────────────┘    └─────────────┘    └─────────────┘  
↑ Real-time data ↑ Model update ↑
    └────────────────┼────────────────┘  
             ┌──────────────────────┐  
│ Distributed Message Bus │
             └──────────────────────┘  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.2 Local decision optimization
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Local gateway rules engine (real-time optimization)
func localEngine(rule: Rule, sensorData: Data) {
    if rule.sensor == "temp" &amp;amp;&amp;amp; sensorData.temp &amp;gt; rule.value {
// Direct control of the device (no cloud delay)
        DeviceController.execute(rule.device, rule.operation, rule.param)

// Asynchronously reporting to the cloud
        uploadToCloud(rule, sensorData)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Practical optimization and avoiding pits
&lt;/h2&gt;

&lt;h3&gt;
  
  
  4.1 Three-pronged performance optimization
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Rules precompilation&lt;/strong&gt;: Compile DSL rules into bytecode at startup to improve execution efficiency&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Conditional short circuit&lt;/strong&gt;: Multi-conditional rules are sorted by hit rate, and invalid judgment is terminated in advance&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hot rule cache&lt;/strong&gt;: High-frequency rules resident in memory, reducing duplicate analysis&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  4.2 Pit avoidance guide
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Syntax Ambiguity&lt;/strong&gt;: Avoid similar syntax (such as &lt;code&gt;set=24&lt;/code&gt; and &lt;code&gt;set 24&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Concurrent conflict&lt;/strong&gt;: Add an execution queue when multiple rules are triggered to avoid device competition&lt;/li&gt;
&lt;li&gt;** Version compatibility**: When the rule syntax changes, the old syntax compatibility layer is retained.&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>HarmonyOS Agent DSL Practical Battle: A Breakthrough in Native AI Application Development</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:05:25 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-agent-dsl-practical-battle-a-breakthrough-in-native-ai-application-development-36m4</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-agent-dsl-practical-battle-a-breakthrough-in-native-ai-application-development-36m4</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As one of the first developers to connect to Harmony Agent DSL, they used it to achieve intelligent linkage of devices in smart home appliance projects.This article combines practical experience to share how Agent DSL lowers the threshold for AI development and achieves a leap from single function to multi-agent collaboration.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. The ice-breaking journey of native AI development
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Three major dilemmas of traditional development
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Frame fragmentation&lt;/strong&gt;: You need to master multiple sets of frameworks such as TensorFlow Lite, ML Kit, etc.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Difficult to cross-end adaptation&lt;/strong&gt;: The AI ​​capabilities of mobile phones/watches/home appliances vary greatly, and the adaptation cost is high&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Real-time bottleneck&lt;/strong&gt;: Cloud AI call latency is high, local model deployment is complex&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  1.2 Agent DSL breaking point
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Unified Development Model&lt;/strong&gt;: A set of DSL is suitable for all Hongmeng devices&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Native Integration&lt;/strong&gt;: Deeply integrating Hongmeng distributed capabilities&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Low code threshold&lt;/strong&gt;: AI logic is separated from business logic, and non-AI developers can also get started&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Agent DSL core features practical combat
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 Minimalist definition of an agent
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Weather intelligent body (get weather and intelligent recommendation)
agent WeatherAgent {
// Basic ability: obtain weather
    func getWeather(city: String) -&amp;gt; WeatherData {
// Call Hongmeng Weather Service
        let data = HmsWeatherService.fetch(city)
        return data
    }

// Intelligent capability: Recommended according to weather
    func getRecommendation(weather: WeatherData) -&amp;gt; String {
        if weather.temp &amp;gt; 30 {
Return "It is recommended to turn on the air conditioner"
        } else if weather.rainfall &amp;gt; 5 {
return "Remember to bring an umbrella"
        }
return "Please be the weather"
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.2 Multi-agent collaborative programming
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Smart home central control intelligent body
agent HomeController {
    private let weatherAgent = WeatherAgent()
    private let acAgent = AirConditionerAgent()
    private let lightAgent = LightAgent()

    func autoAdjust() {
// 1. Get the weather
let weather = weatherAgent.getWeather("Beijing")
// 2. Coordinate the air conditioner
        if weather.temp &amp;gt; 28 {
            acAgent.setTemp(24)
        }
// 3. Turn on the lights when the weather is dark
        if weather.light &amp;lt; 300 {
            lightAgent.turnOn()
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.3 Distributed Agent Communication
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Cross-device collaboration (mobile phone and air conditioner)
agent MobileController {
    func controlAc(acId: String, temp: Int) {
// Distributed call to the air conditioner intelligent body
        let acAgent = AgentFinder.find("air_conditioner:\(acId)")
        acAgent.send(SetTemperature(temp: temp))
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Practical cases: intelligent sleep system
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Armor Architecture Design
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌─────────────┐    ┌─────────────┐    ┌─────────────┐  
│ Sleep Monitoring Agent │───→│ Data Analysis Agent │───→│ Equipment Control Agent │
│ (Watch end) │ │ (Mobile end) │ │ (Home appliance end) │
└─────────────┘    └─────────────┘    └─────────────┘  
        ↑                ↑                ↑  
        └────────────────┼────────────────┘  
                 ┌──────────────────────┐  
│ Distributed Message Bus │
                 └──────────────────────┘  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.2 Core Code Implementation
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Sleep monitoring intelligent body (watch end)
agent SleepMonitor {
    func monitor() -&amp;gt; SleepData {
// Read bracelet sensor data
        let data = WearableSensor.read()
        return data
    }
}

// Data analysis intelligent body (mobile terminal)
agent SleepAnalyzer {
    func analyze(data: SleepData) -&amp;gt; AdjustmentPlan {
// AI analyzes sleep quality
        if data.deepSleep &amp;lt; 1.5.hours {
            return Plan(light: 300, temp: 26)
        }
        return Plan(light: 200, temp: 24)
    }
}

// Equipment control intelligent body (home appliance terminal)
agent DeviceController {
    func execute(plan: AdjustmentPlan) {
        Light.setBrightness(plan.light)
        AC.setTemperature(plan.temp)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Performance optimization and best practices
&lt;/h2&gt;

&lt;h3&gt;
  
  
  4.1 Optimization strategy for resource-constrained devices
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Model lightweight&lt;/strong&gt;: Use Hongmeng Lightweight AI compiler to optimize model size&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Local priority&lt;/strong&gt;: Common models are cached locally in the device, reducing cloud calls&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Async processing&lt;/strong&gt;: Use &lt;code&gt;async&lt;/code&gt; to avoid blocking the UI by using non-real-time tasks&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  4.2 Pit avoidance guide
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Communication overhead&lt;/strong&gt;: Reduce frequent communication between agents and merge batch messages&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Status Management&lt;/strong&gt;: Avoid excessive maintenance of agents, and give priority to stateless design&lt;/li&gt;
&lt;li&gt;** Version compatible**: When the agent interface is changed, it remains backward compatible&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>HarmonyOS variable survival rules: a practical guide to the memory model from variability to the practical</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:05:10 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-variable-survival-rules-a-practical-guide-to-the-memory-model-from-variability-to-the-34kn</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-variable-survival-rules-a-practical-guide-to-the-memory-model-from-variability-to-the-34kn</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As an old driver who was cheated by variables in Hongmeng development, he once caused equipment data to be confused due to misuse of reference types, and was tortured by the compiler's conservative strategy.This article combines practical experience to analyze the survival rules of the Cangjie language variable system to help you avoid variable-related pitfalls.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Let/var's philosophy of survival: the principle of immutable priority
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Life and death line in concurrent scenarios
&lt;/h3&gt;

&lt;p&gt;Immutable variables are life-saving characters in concurrency, and mutable variables are time bombs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Dangerous variable variables (concurrent scenarios)
var counter = 0
let thread1 = async { counter += 1 }
let thread2 = async { counter += 1 }
awaitAll([thread1, thread2])
println(counter) // Possible output 1 (race condition)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Safe immutable variables (functional style)
let initial = 0
let result = awaitAll([
    async { initial + 1 },
    async { initial + 1 }
]).reduce(0, +)
println(result) // Ensure output 2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Practical principles&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use &lt;code&gt;let&lt;/code&gt; first to avoid race conditions for sharing data&lt;/li&gt;
&lt;li&gt;When it must be variable, wrap it with &lt;code&gt;AtomicReference&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  2. Value type vs reference type: survival form in memory
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 Memory survival difference between struct and class
&lt;/h3&gt;

&lt;p&gt;The value type is like an independent living body, and the reference type is like an egg twin:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Value type struct (Survival independently)
struct Point {
    var x: Int
    var y: Int
}

let p1 = Point(x: 1, y: 2)
let p2 = p1 // Generate independent replica
p2.x = 3
println(p1.x) // Output 1 (not affected)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph TD
A[stack memory] --&amp;gt; B[p1(x:1,y:2)]
A --&amp;gt; C[p2(x:1,y:2)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Reference type class (shared survival)
class Point {
    var x: Int
    init(x: Int) { this.x = x }
}

let p1 = Point(x: 1)
let p2 = p1 // Share the same object
p2.x = 3
println(p1.x) // Output 3 (affected)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;graph TD
A[stack memory] --&amp;gt; B[p1(points to heap object)]
A --&amp;gt; C[p2 (points to the same bunch of objects)]
D[heap memory] --&amp;gt; E[object(x:1, then becomes 3)]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.2 Survival strategy selection
&lt;/h3&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Scene&lt;/th&gt;
&lt;th&gt;Select Type&lt;/th&gt;
&lt;th&gt;Survival Advantages&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Small data independent operation&lt;/td&gt;
&lt;td&gt;struct&lt;/td&gt;
&lt;td&gt;efficient replication, no sharing risk&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Big data sharing operation&lt;/td&gt;
&lt;td&gt;class&lt;/td&gt;
&lt;td&gt;High memory efficiency and convenient sharing&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  3. The conservative survival strategy of the compiler
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Variable survival crisis in try-catch
&lt;/h3&gt;

&lt;p&gt;Compilers like overprotected parents must ensure that the variable "living":&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Compiler error case
let a: String
try {
    a = "success"
} catch {
// The compiler believes that a may not be initialized
    // Error: Variable 'a' used before being initialized
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Survival Plan&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Initialize in advance: &lt;code&gt;let a: String = ""&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Use optional type: &lt;code&gt;let a: String? = nil&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  3.2 The rules of variable survival in closures
&lt;/h3&gt;

&lt;p&gt;Closure capture variables are like "parasitic", and you need to pay attention to your life cycle:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func createTimer() -&amp;gt; () -&amp;gt; Void {
    var count = 0
    return {
        count += 1
        println(count)
    }
}

let timer = createTimer()
timer() // output 1
timer() // Output 2 (count is captured by closure and remains state)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Variable survival practice: bank account cases
&lt;/h2&gt;

&lt;h3&gt;
  
  
  4.1 Value Type Account (Safe but Inefficient)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;struct BankAccount {
    let id: String
    var balance: Double

    func withdraw(amount: Double) -&amp;gt; BankAccount {
// Return to a copy of the new account
        return BankAccount(id: id, balance: balance - amount)
    }
}

let account = BankAccount(id: "123", balance: 1000)
let newAccount = account.withdraw(amount: 200)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.2 Reference type account (efficient but cautious)
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class BankAccount {
    let id: String
    var balance: Double

    init(id: String, balance: Double) {
        self.id = id
        self.balance = balance
    }

    func withdraw(amount: Double) {
balance -= amount // directly modify the status
    }
}

let account = BankAccount(id: "123", balance: 1000)
account.withdraw(amount: 200)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Guide to avoiding variable survival
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Immutable priority&lt;/strong&gt;: Use &lt;code&gt;let&lt;/code&gt; first for 90% of variables, and then use &lt;code&gt;var&lt;/code&gt; when it is necessary to change it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Value type priority&lt;/strong&gt;: Use &lt;code&gt;struct&lt;/code&gt; for small data, and use &lt;code&gt;class&lt;/code&gt; for big data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Closure Trap&lt;/strong&gt;: Avoid catching mutable variables in closures, and use immutable + functional style instead.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Compiler-friendly&lt;/strong&gt;: Follow the compiler conservative strategy and handle variable initialization in advance&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
    <item>
      <title>HarmonyOS AIoT规则引擎实战：DSL Kit构建智能联动系统</title>
      <dc:creator>SameX</dc:creator>
      <pubDate>Fri, 27 Jun 2025 06:04:54 +0000</pubDate>
      <link>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-aiotgui-ze-yin-qing-shi-zhan-dsl-kitgou-jian-zhi-neng-lian-dong-xi-tong-51jc</link>
      <guid>https://dev.to/xun_wang_6384a403f9817c2/harmonyos-aiotgui-ze-yin-qing-shi-zhan-dsl-kitgou-jian-zhi-neng-lian-dong-xi-tong-51jc</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;As a developer who has struck a trap with DSL Kit in the Hongmeng IoT project, the air conditioner has automatically cooled in winter due to rule syntax errors.This article shares how to use the Cangjie language DSL Kit to build an intelligent rule engine to achieve a simple trigger from "temperature &amp;gt; 30 to turn on the air conditioner" to intelligent linkage of AI dynamic parameter adjustment.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Rule Engine Core: Practical Design of DSL Syntax
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1.1 Minimalist definition of BNF syntax
&lt;/h3&gt;

&lt;p&gt;Use DSL Kit to define the syntax of air conditioning linkage rules (40% simplified than the original solution):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rule = "when" condition "then" action
condition = sensor operator value
action = device operation [param]

sensor = "temp_sensor" | "humidity_sensor"
device = "aircon" | "fan"
operator = "&amp;gt;" | "&amp;lt;" | "=="
operation = "on" | "off" | "set_temp"
param = number
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Practical rules example&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;When temp_sensor &amp;gt; 28 then aircon set_temp 24 // The temperature exceeds 28℃ and set to 24℃
When humidity_sensor &amp;lt; 30 then fan on // Moisture is lower than 30%
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  1.2 Pits and solutions for syntax analysis
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Training case&lt;/strong&gt;: Unprocessed parameter type leads to rule error&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Correct parser implementation (the key is type verification)
func parseRule(ruleStr: String) -&amp;gt; Rule? {
    let parts = ruleStr.split(" ")
    if parts.size &amp;lt; 5 { return nil }

// Type verification (such as temperature value must be 16-30)
    if parts[4] is Number &amp;amp;&amp;amp; parts[4].toInt() in 16..30 {
        return Rule(
            sensor: parts[1],
            operator: parts[2],
            value: parts[3].toInt(),
            device: parts[5],
            operation: parts[6],
            param: parts.size &amp;gt; 7 ? parts[7].toInt() : nil
        )
    }
    return nil
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2. AI integration: Dynamic tuning of Agent DSL
&lt;/h2&gt;

&lt;h3&gt;
  
  
  2.1 Implementation of intelligent parameter adjustment
&lt;/h3&gt;

&lt;p&gt;Define climate agents (30% less code than the original plan):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@agent ClimateAgent {
// Intelligent temperature regulation logic (adjust according to personnel activities dynamics)
    func optimizeTemp(sensorData: SensorData) -&amp;gt; Int {
        let baseTemp = 26
        if sensorData.personCount &amp;gt; 3 {
return baseTemp - 2 // Reduce 2℃ when multiple people
        } else if sensorData.lightIntensity &amp;gt; 800 {
return baseTemp + 1 // Increase by 1℃ during strong light
        }
        return baseTemp
    }
}

// Called in the rules engine
let agent = spawn(ClimateAgent())
let targetTemp = agent.ask(optimizeTemp(sensorData))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  2.2 Optimization techniques for real-time linkage
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Practical Strategy&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Cached recent parameters&lt;/strong&gt;: Avoid frequent AI calculations&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Threshold anti-shake&lt;/strong&gt;: Adjustment will not be triggered when the temperature fluctuates ±1℃&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Time Strategy&lt;/strong&gt;: Automatically increase the temperature setting value at night
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Temperature adjustment with anti-shake
func adjustWithDebounce(current: Int, target: Int) {
if abs(current - target) &amp;gt; 1 { // Adjust if it exceeds 1℃
        setAirconTemp(target)
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  3. Compilation optimization: Early intercept rule errors
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Testing of attribute syntax
&lt;/h3&gt;

&lt;p&gt;Embed check logic in BNF (compile-intercept error):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rule = "when" condition "then" action {
checkTempAction(action) // Check the temperature parameter range
}

action = "aircon" "set_temp" temp {
temp &amp;gt;= 16 &amp;amp;&amp;amp; temp &amp;lt;= 30 // The temperature must be between 16-30
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Error Example Intercept&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;When temp_sensor &amp;gt; 30 then aircon set_temp 35 // Compile error: Temperature 35 is out of range
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.2 Three-pronged approaches to performance optimization
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Rules precompilation&lt;/strong&gt;: Compile DSL rules into bytecode at startup&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Conditional Short Circuit&lt;/strong&gt;: Multi-conditional rules are sorted by hit rate&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Hot rule cache&lt;/strong&gt;: High frequency rule resident memory
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Rule precompilation example
let rules = compileRules([
    "when temp&amp;gt;28 then aircon set_temp 24",
    "when humidity&amp;lt;30 then fan on"
])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Practical results and guide to avoid pits
&lt;/h2&gt;

&lt;h3&gt;
  
  
  4.1 Project implementation effect
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Improved development efficiency: The rule configuration time is shortened from 2 days to 4 hours&lt;/li&gt;
&lt;li&gt;Failure rate drops: 85% reduction in runtime rule errors&lt;/li&gt;
&lt;li&gt;Energy-saving effect: AI adjusts reference fixed rules to save energy by 12%&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  4.2 Pit avoidance list
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Parameter boundary&lt;/strong&gt;: All numerical parameters must define upper and lower limit verification&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Concurrency Control&lt;/strong&gt;: Add an execution queue when multiple rules are triggered&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Downgrade policy&lt;/strong&gt;: Automatically switch to basic rules when AI module fails&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
  </channel>
</rss>
