miningos-tpl-wrk-electricity
v1.0.0
Published
MiningOS Template Electricity
Downloads
268
Readme
miningos-tpl-wrk-electricity
Template worker for electricity monitoring, spot price forecasting, and mining profitability calculations in MiningOS.
Table of Contents
- Overview
- Prerequisites
- Installation
- Configuration
- Starting the Worker
- Architecture
- API Reference
- Development
- Troubleshooting
- Contributing
Overview
The Electricity Worker Template provides a foundation for building electricity monitoring workers that:
- Track electricity costs and revenue for mining operations
- Process spot price forecast data
- Calculate mining profitability based on hashrate and power consumption
- Store and retrieve historical energy data
- Provide 24-hour uptime range calculations
This is a template repository - most methods are no-ops designed to be overridden in concrete implementations for specific electricity providers or data sources.
Prerequisites
- Node.js >= 20.0
- Understanding of Hyperswarm RPC (for P2P communication)
- Access to electricity data sources (for concrete implementations)
Installation
- Clone the repository:
git clone https://github.com/tetherto/miningos-tpl-wrk-electricity.git
cd miningos-tpl-wrk-electricity- Install dependencies:
npm install- Setup configuration files:
bash setup-config.sh
# For test configurations as well:
bash setup-config.sh --testConfiguration
Common Configuration (config/common.json)
Basic worker configuration:
{
"dir_log": "logs",
"debug": 0
}Network Configuration (config/facs/net.config.json)
Configure Hyperswarm network settings for RPC communication with other workers.
Storage Configuration (config/facs/store.config.json)
Configure Hyperbee database settings for persistent storage.
Note: After running setup-config.sh, edit the generated config files with your specific settings.
Starting the Worker
Development Mode
node worker.js --wtype wrk-electricity-rack --env development --rack rack-0Production Mode
node worker.js --wtype wrk-electricity-rack --env production --rack rack-1Parameters
--wtype: Worker type identifier (e.g.,wrk-electricity-rack)--env: Environment (development,production)--rack: Rack identifier (e.g.,rack-0,rack-1)
Architecture
Core Components
Worker Class: WrkElectricityRack
Main worker class that extends TetherWrkBase from tether-wrk-base.
File: workers/rack.electricity.wrk.js
Key responsibilities:
- Exposes RPC endpoints for electricity data retrieval
- Manages worker settings persistence
- Handles data queries via
getWrkExtDatamethod
Settings Management
File: workers/lib/wrk-fun-settings.js
Provides:
getSettings()- Retrieve worker settings from Hyperbee storagesaveSettingsEntries(entries)- Update and persist settings
Data Storage
Uses Hyperbee (SQLite-backed key-value store) via hp-svc-facs-store:
- Storage location:
store/${rack}-db - Settings key:
settings_00 - Provides fast, persistent storage for worker configuration
RPC Communication
Workers communicate via Hyperswarm RPC:
- Uses public keys for peer discovery
- Exposes
getWrkExtDatamethod for data queries - Supports
getWrkSettingsandsaveWrkSettingsfor configuration
API Reference
Primary RPC Method: getWrkExtData
The main endpoint for retrieving electricity data. All requests must include a query object with a key property.
Request Structure:
{
query: {
key: string, // Required: determines operation
// Additional properties depend on key type
},
data?: any // Optional: used for certain operations
}Supported Query Keys
1. margin
Retrieves the configured margin value for profitability calculations.
Payload:
{
query: { key: 'margin' }
}Returns: Number representing margin percentage or 0 if not configured.
2. revenue-estimates
Retrieves weekly revenue estimates from the database.
Payload:
{
query: {
key: 'revenue-estimates',
start: number, // Unix timestamp (ms) - range start
end: number, // Unix timestamp (ms) - range end
fields?: object // Optional: projection fields
}
}Returns: Array of weekly revenue estimate objects.
3. spot-price
Retrieves spot price forecast data for a given time range.
Payload:
{
query: {
key: 'spot-price',
start: number, // Unix timestamp (ms) - range start
end: number, // Unix timestamp (ms) - range end
fields?: object // Optional: projection fields
}
}Returns: Array of spot price forecast objects (timestamp, USD/MWh).
4. uptimeRange
Calculates 24-hour uptime range metrics based on provided data.
Payload:
{
query: { key: 'uptimeRange' },
data: any // Required: uptime data to analyze
}Returns: Calculated 24-hour uptime range metrics.
Note: This is the only fully implemented method in the template.
6. stats
Retrieves current electricity statistics.
Payload:
{
query: {
key: 'stats',
fields?: object // Optional: projection fields
}
}Returns: Comprehensive stats object containing:
- Active and reactive energy (1-hour and 15-minute intervals)
- UTE energy data
- Spot prices
- Next hour energy values
- Hashrate and consumption metrics
7. cost-revenue
Retrieves historical hourly cost and revenue data with optional aggregation.
Payload:
{
query: {
key: 'cost-revenue',
start: number, // Unix timestamp (ms) - range start
end: number, // Unix timestamp (ms) - range end
fields?: object, // Optional: projection fields
aggrDaily?: boolean, // Optional: aggregate by day
aggrHourly?: boolean // Optional: aggregate by hour
}
}Returns: Array of cost-revenue objects (raw or aggregated).
8. stats-history
Retrieves aggregated historical statistics grouped by day or month.
Payload:
{
query: {
key: 'stats-history',
start: number, // Unix timestamp (ms) - range start
end: number, // Unix timestamp (ms) - range end
groupRange: string, // Required: 'D1' (daily) or 'MONTH1' (monthly)
dataInterval: string, // Required: '15min' or '1h'
fields?: object // Optional: projection fields
}
}Returns: Array of aggregated statistics containing:
- Aggregated active and reactive energy values
- Aggregated spot price (averaged)
- Aggregated UTE energy
- Timestamp and grouping label
- Count of records aggregated
Error Handling
The method throws errors for invalid inputs:
ERR_QUERY_INVALID: Missing or invalid query objectERR_KEY_INVALID: Missing key property in query
Using the RPC CLI
Interact with the worker using hp-rpc-cli:
# Get margin value
hp-rpc-cli -s RPC_KEY \
-m 'getWrkExtData' \
-d '{"query": {"key": "margin"}}'
# Get cost-revenue with daily aggregation
hp-rpc-cli -s RPC_KEY \
-m 'getWrkExtData' \
-d '{"query": {"key": "cost-revenue", "start": 1697500800000, "end": 1697587200000, "aggrDaily": true}}'
# Get stats history grouped by day
hp-rpc-cli -s RPC_KEY \
-m 'getWrkExtData' \
-d '{"query": {"key": "stats-history", "start": 1697500800000, "end": 1700179200000, "groupRange": "D1", "dataInterval": "1h"}}'
## Development
### Running Tests
```bash
npm test # Run all tests (currently runs lint)
npm run lint # Check code style (Standard.js)
npm run lint:fix # Auto-fix linting issuesProject Structure
.
├── config/ # Configuration files
│ ├── common.json.example
│ └── facs/ # Facility configs (net, store, etc.)
├── workers/
│ ├── rack.electricity.wrk.js # Main worker class
│ └── lib/
│ ├── wrk-fun-settings.js # Settings persistence
│ └── utils.js # Utility functions
├── mock/
│ └── mock-control-agent.js # Mock service for testing
├── setup-config.sh # Config file generator
└── worker.js # Entry pointImplementing a Concrete Worker
This is a template - override the no-op methods in your implementation:
- Extend
WrkElectricityRackclass - Implement the query methods:
getRevenueEstimates(req)getSpotPrice(req)calcCostAndRevenue(req)getStats(req)getCostRevenue(req)getStatsHistory(req)
- Add your electricity data source integration
- Configure data polling/fetching schedules
- Add appropriate error handling and logging
Troubleshooting
Common Issues
Configuration files missing
- Run
bash setup-config.shto generate from templates - Verify all
.examplefiles have been processed
- Run
Worker fails to start
- Check that
--rackparameter is provided - Verify Node.js version >= 16.0
- Review logs in
logs/directory (if configured)
- Check that
RPC connection failures
- Verify network configuration in
config/facs/net.config.json - Check that Hyperswarm network is accessible
- Ensure RPC public keys are correct
- Verify network configuration in
Storage errors
- Check
store/${rack}-dbdirectory exists and is writable - Verify storage configuration in
config/facs/store.config.json - Ensure sufficient disk space
- Check
Methods returning undefined
- Remember: most methods are no-ops in this template
- Implement concrete methods in your derived class
- Only
uptimeRangeis fully implemented
Contributing
Contributions are welcome and appreciated!
How to Contribute
- Fork the repository
- Create a new branch for your feature or fix:
git checkout -b feature/your-feature-name - Make your changes and ensure tests pass:
npm test - Push to your fork:
git push origin feature/your-feature-name - Open a Pull Request describing what you changed and why
Guidelines
- Follow Standard.js code style (
npm run lint) - Add tests for new functionality
- Keep PRs focused—one feature or fix per pull request
- Update documentation as needed
- Ensure all tests pass before submitting
- Consider backward compatibility for template users
