$ npm install miningos-tpl-wrk-electricityTemplate worker for electricity monitoring, spot price forecasting, and mining profitability calculations in MiningOS.
The Electricity Worker Template provides a foundation for building electricity monitoring workers that:
This is a template repository - most methods are no-ops designed to be overridden in concrete implementations for specific electricity providers or data sources.
git clone https://github.com/tetherto/miningos-tpl-wrk-electricity.git
cd miningos-tpl-wrk-electricity
npm install
bash setup-config.sh
# For test configurations as well:
bash setup-config.sh --test
Basic worker configuration:
{
"dir_log": "logs",
"debug": 0
}
Configure Hyperswarm network settings for RPC communication with other workers.
Configure Hyperbee database settings for persistent storage.
Note: After running setup-config.sh, edit the generated config files with your specific settings.
node worker.js --wtype wrk-electricity-rack --env development --rack rack-0
node worker.js --wtype wrk-electricity-rack --env production --rack rack-1
--wtype: Worker type identifier (e.g., wrk-electricity-rack)--env: Environment (development, production)--rack: Rack identifier (e.g., rack-0, rack-1)WrkElectricityRackMain worker class that extends TetherWrkBase from tether-wrk-base.
File: workers/rack.electricity.wrk.js
Key responsibilities:
getWrkExtData methodFile: workers/lib/wrk-fun-settings.js
Provides:
getSettings() - Retrieve worker settings from Hyperbee storagesaveSettingsEntries(entries) - Update and persist settingsUses Hyperbee (SQLite-backed key-value store) via hp-svc-facs-store:
store/${rack}-dbsettings_00Workers communicate via Hyperswarm RPC:
getWrkExtData method for data queriesgetWrkSettings and saveWrkSettings for configurationgetWrkExtDataThe 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
}
marginRetrieves the configured margin value for profitability calculations.
Payload:
{
query: { key: 'margin' }
}
Returns: Number representing margin percentage or 0 if not configured.
revenue-estimatesRetrieves 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.
spot-priceRetrieves 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).
uptimeRangeCalculates 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.
statsRetrieves current electricity statistics.
Payload:
{
query: {
key: 'stats',
fields?: object // Optional: projection fields
}
}
Returns: Comprehensive stats object containing:
cost-revenueRetrieves 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).
stats-historyRetrieves 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:
The method throws errors for invalid inputs:
ERR_QUERY_INVALID: Missing or invalid query objectERR_KEY_INVALID: Missing key property in queryInteract 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 issues
.
├── 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 point
This is a template - override the no-op methods in your implementation:
WrkElectricityRack classgetRevenueEstimates(req)getSpotPrice(req)calcCostAndRevenue(req)getStats(req)getCostRevenue(req)getStatsHistory(req)Configuration files missing
bash setup-config.sh to generate from templates.example files have been processedWorker fails to start
--rack parameter is providedlogs/ directory (if configured)RPC connection failures
config/facs/net.config.jsonStorage errors
store/${rack}-db directory exists and is writableconfig/facs/store.config.jsonMethods returning undefined
uptimeRange is fully implementedContributions are welcome and appreciated!
git checkout -b feature/your-feature-name
npm test
git push origin feature/your-feature-name
npm run lint)