我写了一个smart contract,用于从树莓派发送传感器数据并获取值。该代码可以正常工作。 然后我编写了一个web3js来检索值并显示在网页上,代码为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="main.css">
<!-- <script src="./node_modules/web3/dist/web3.min.js"></script>-->
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
</head>
<body>
<div class="container">
<h1>Smart Maintenance</h1>
<div>
<p id="sData">value in the block</p>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script>
//var Web3 = require('web3')
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
//set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:8545"));
}
var abi= [
{
"constant": false,
"inputs": [],
"name": "getSensorData",
"outputs": [
{
"name": "",
"type": "int256"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"name": "_sensorData",
"type": "int256"
}
],
"name": "setSensorData",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [
{
"name": "_sensorData",
"type": "int256"
}
],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
}
]
var ContractAddress = '0x2f5beA7A525074f64929F6D237d4A9dA1B182ADC';
var myAbi = web3.eth.contract(abi);
var myfunction = myAbi.at(ContractAddress);
//const StoreIntegerValue = web3.eth.Contract({abi}, ContractAddress);
console.log(myfunction);
myfunction.getSensorData.call(function(error, result){
if(!error)
{
$("#sData").text(result + ' degrees' );
console.log(result);
}
else
console.error(error);
});
//var sensData = myfunction.getSensorData.call();
//console.log(sensData)
</script>
</body>
</html>`
从console.log(myfunction)中我可以看到合同和方法都有联系。但是我没有看到所需的console.log(result)输出。 output。我尝试了不同的方法,但没有帮助。请帮帮我 注意:我想在树莓派中调用方法setSensorData。然后稍后在私有区块链中从另一台PC调用getSensorData到webUI。因此,当前在localhost中分别测试setSensorData和getSensorData。