I need code for getting data from bluemix which is sent by this code
import RPi.GPIO as GPIO
import dht11
import time
import datetime
import ibmiotf.device
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
1
client.connect()
# read data using pin GPIO4
instance = dht11.DHT11(pin=4)
while True:
result = instance.read()
if result.is_valid():
print("Last valid input: " + str(datetime.datetime.now()))
temp=(" %d C" % result.temperature)
print("temperature:" +temp)
humid=("%d %%" % result.humidity)
print("Humidity:" +humid)
# print("Temperature: %d C" % result.temperature)
# print("Humidity: %d %%" % result.humidity)
print("Data is published into the cloued")
Data={'Temperature' :temp, 'Humidity' :humid }
client.publishEvent("status", "json", Data)
time.sleep(1)
you can use NodeRed to add some node(insert, function, iotout) to publish the data to iot platform(publish it as device type) into a topic then in the PI with pyhton subscribe to that topic as an application... that should work just fine. All the connection/publish/subscribing/topics details can be found here:
https://console.ng.bluemix.net/docs/services/IoT/index.html
You connect as a device -> import ibmiotf.device. A device can send events and receive commands. It can't receive events. To do this you need to connect as an application. You will import ibmiotf.application and have something like:
options = ibmiotf.application.ParseConfigFile(configFilePath)
appClient = ibmiotf.application.Client(options)
appClient.connect()
appClient.subscribeToDeviceEvents()
The config file should be like:
[application]
org=orgId
id=myApplication
auth-method=apikey
auth-key=key
auth-token=token
Where the auth-key/auth-token comes from the Apps part of your platform. You'll have to generate a set to connect as an application. The auth-method should be left as apikey.
That will list every event that arrives to your platform. You can make it more granular. See the api guide which also references a sample app on github.
Related
I'm trying to use my raspberry pi as a client for modbus communication between it and a S7-1200 Siemens plc. I got it to read integers from holding register, but not strings. When I try to search for a solution online on how to read strings from the plc holding register nothing useful comes up. I tried a program online that is supposed to be able to do it but I just keep getting an error every time I run it. Can anyone help? I have the code for the program and the error message below.
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.constants import Endian
from pymodbus.compat import iteritems
if __name__ == '__main__':
client = ModbusClient("192.168.0.1", port=502, auto_open=True)
client.connect()
result = client.read_holding_registers(1, 1, unit=1)
print("Result : ",result)
decoder = BinaryPayloadDecoder.fromRegisters(result.registers, byteorder=Endian.Big, wordorder=Endian.Big)
decoded = {
'name': decoder.decode_string(10).decode(),
}
for name, value in iteritems(decoded):
print ("%s\t" % name, value)
client.close()
Error Message
Data Register
PLC MB Server Block Setup
for example you want to read speed of a asynchronous motor and you use a driver. You have a raspberry pi. You use python and Modbus TCP Protocol .
speed of motor is registered 40001.
result = client.read_holding_registers(1, 1, unit=1) you can read just 40001 adress.
result = client.read_input_registers(0x01,1, unit=0x01) you can read just 30001 adress.
Your Decoding is fine.
It's your setup & request that's the issue.
PLC Setup looks wrong.
You are also only requesting 1 register to read.
Your request is not getting any response (including error).
Coke = b'436f6b65' = [17263, 27493]
Pizza = b'50697a7a6100' = [20585, 31354, 24832]
Cookies = b'436f6f6b69657300' = [17263, 28523, 26981, 29440]
Pad out with 0's to keep register lengths the same.
Store in plc Modbus registers that can be read.
Coke = b'436f6b6500000000' = [17263, 27493, 0, 0]
Pizza = b'50697a7a61000000' = [20585, 31354, 24832, 0]
Cookies = b'436f6f6b69657300' = [17263, 28523, 26981, 29440]
Request 4 registers per word and decode.
you can't take strings value from modbus communication
I've made a python program in Raspberry Pi 3 Model B that's supposed to connect to Google Cloud IoT Core with MQTT-protocol and get configurations. Sending data to Core has worked so far, but I just can't figure out how configuring works! Here's a code that's just supposed to get a config:
import time
import datetime
import jwt
import ssl
import json
import paho.mqtt.client as mqtt
time_now = datetime.datetime.utcnow()
#make key
token = {'iat' : time_now ,
'exp' : time_now + datetime.timedelta(minutes=60),
'aud' : "[PROJECT]"}
r = open("[PRIVATE KEY]", 'r')
pub_key = r.read()
jwt_key = jwt.encode(token, pub_key, algorithm='RS256')
#connect to iot-core
client = mqtt.Client(client_id='projects/[PROJECT]/locations/[LOCATION]/registries/[REGISTER]/devices/[DEVICE]')
client.username_pw_set(username='unused', password=jwt_key)
client.tls_set(ca_certs='/home/pi/.local/lib/python2.7/site-packages/grpc/_cython/_credentials/roots.pem', tls_version=ssl.PROTOCOL_TLSv1_2)
client.connect("mqtt.googleapis.com", 8883)
#configure and change state
state = 0
print state #naturally shows 0
print client.subscribe([DEVICE]/config, qos=1) #doesn't print custom config either, just (0,1)
print state #still shows 0
configuration in Iot Core device id is:
{ "state": 1 }
Even after running the program, the device's "state"-variable stays at 0 and the Core's Configuration & State History state that the CONFIG is "Not yet acknowledged by the device"
How do I get the device's "state" variable change from 0 to 1 from Core?
You have done the half of the job. 2 remarks.
It's maybe a detail, but you name your private key pub_key. And you don't close the file.
Based on this tutorial, you only subscribe to the MQTT. The return tuple (0,1) means MQTT_ERR_SUCCESS on QOS = 1. Thus your are connected. Great! Now, do the second part: consume the messages in the channel, and make your logic (according with the received message, change the state in your app if it's your use case)
Referencing the following video: An OPC UA sample server in written in python using its opcua module
I am trying to implement this server on my own, so that I can later make modifications to it. I have PyDev for Eclipse installed as used in the video.
Here is the code used in the video:
from opcua import Server
from random import randint
import datetime
import time
server = Server()
url = "opc.tcp://192.168.0.8:4840"
server.set_endpoint(url)
name = "OPC_SIMULATION_SERVER"
addspace = server.register_namespace(name)
node = server.get_objects_node()
Param = node.add_object(addspace, "Parameters")
Temp = Param.add_variable(addspace, "Temperature", 0)
Press = Param.add_variable(addspace, "Pressure", 0)
Time = Param.add_variable(addspace, "Time", 0)
Temp.set_writable()
Press.set_writable()
Time.set_writable()
server.start()
print("Server started at {}".format(url))
while True:
Temperature = randint(10,50)
Pressure = randint(200, 999)
TIME = datetime.datetime.now()
print(Temperature, Pressure, TIME)
Temp.set_value(Temperature)
Press.set_value(Pressure)
Time.set_value(TIME)
time.sleep(2)
When I try to run this code, I get the following errors, which appear to be related to one another:
Error Image
If you could help me identify the source of errors, and possible resolutions to them I would appreciate it.
Edit: I was able to configure the server and it ran as expected. However, I now wish to connect it to a client to read in the data. When I try to do this, the connection is established but no data is read in. What are some potential fixes to this issue?
I'm currently working with raspberry pi and using DHT11 to read temperature and humidity values every second. I have to save these values into a database in real time.
here's my code that showing sensor data every second, i don't know how and where do i insert lines of connection to database.
import RPi.GPIO as GPIO
import dht11
import time
import datetime
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
# read data using pin 7
instance = dht11.DHT11(pin=4)
while True:
result = instance.read()
if result.is_valid():
print("Last valid input: " + str(datetime.datetime.now()))
print("Temperature: %d C" % result.temperature)
#print("Temperature: %d F" % ((result.temperature * 9/5) + 32))
print("Humidity: %d %%" % result.humidity)
time.sleep(1)
first install MySQL db on your system then use PyMySQL or any other library for connection to MySQL from python if using PyMySQL go through this DOC
install library using
pip install PyMySQL
Make connection once so put connection codes on top your while loop
db = PyMySQL.connect("localhost:port","username","password","database_name" )
cursor = db.cursor()
while True:
use cursor for SQL-QUERY execution inside while loop where you get valid results to be stored
sql = "insert into table_name(id,feild1,feild2) values (1,value1,value2);"
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
change the fields table name and connection information as in database and replace values in INSERT statement to your sensor values
I try to get status from my printer using SNMP protocol
The problem is, I've never used the SNMP and I have trouble understanding how can I get my status like ( PAPER OUT, RIBBON OUT, etc... ).
I configured my printer to enable the SNMP protocol using the community name "public"
I presume SNMP messages are sent on the port 161
I'm using Pysnmp because I want to integrate the python script in my program to listen to my printer and display status if there is a problem with the printer.
For now I've tried this code :
import socket
import random
from struct import pack, unpack
from datetime import datetime as dt
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.proto.rfc1902 import Integer, IpAddress, OctetString
ip = '172.20.0.229'
community = 'public'
value = (1,3,6,1,2,1,25,3,5,1,2)
generator = cmdgen.CommandGenerator()
comm_data = cmdgen.CommunityData('server', community, 1) # 1 means version SNMP v2c
transport = cmdgen.UdpTransportTarget((ip, 161))
real_fun = getattr(generator, 'getCmd')
res = (errorIndication, errorStatus, errorIndex, varBinds) \
= real_fun(comm_data, transport, value)
if not errorIndication is None or errorStatus is True:
print "Error: %s %s %s %s" % res
else:
print "%s" % varBinds
The IP address is the IP of my printer
The problem is the OID: I don't know what to put in the OID field because I have trouble understanding how does OID work.
I found this page but I'm not sure it fits with all printers ==> click here
You need your printer specific MIB file in common case. E.g., printer in my office seems to be not support both oids by your link. Also you can use snmpwalk to get available oids and values on your printer and if you somehow understand which values you need, you can use it for specific instance of your printer.