For a student project I have to record a sample from a 433MHz receiver and send it back to replace the initial button that send it.
I succeed to receive and save it in a pickle file.
But now, I don't know how to send it back...
I've tried different things but nothing's working.
Could you, please, help me do it ?
Here are my codes :
Receive part :
from __future__ import with_statement
from datetime import datetime
import matplotlib.pyplot as pyplot
import RPi.GPIO as GPIO
import pickle
RECEIVED_SIGNAL = [[], []] #[[time of reading], [signal reading]]
MAX_DURATION = 5
RECEIVE_PIN = 23
outputb = open('button_on.pkl', 'w')
outputa = open('time_on.pkl' ,'w')
if __name__ == '__main__':
GPIO.setmode(GPIO.BCM)
GPIO.setup(RECEIVE_PIN, GPIO.IN)
cumulative_time = 0
beginning_time = datetime.now()
print '**Started recording**'
while cumulative_time < MAX_DURATION:
time_delta = datetime.now() - beginning_time
RECEIVED_SIGNAL[0].append(time_delta)
RECEIVED_SIGNAL[1].append(GPIO.input(RECEIVE_PIN))
cumulative_time = time_delta.seconds
print '**Ended recording**'
print len(RECEIVED_SIGNAL[0]), 'samples recorded'
GPIO.cleanup()
print '**Processing results**'
for i in range(len(RECEIVED_SIGNAL[0])):
RECEIVED_SIGNAL[0][i] = RECEIVED_SIGNAL[0][i].seconds + RECEIVED_SIGNAL[0][i].microseconds/1000000.0
print RECEIVED_SIGNAL[0][i] , RECEIVED_SIGNAL[1][i]
A= RECEIVED_SIGNAL[0][i]
B= RECEIVED_SIGNAL[1][i]
outputa.write(str(A))
outputb.write(str(B))
print '**Plotting results**'
pyplot.plot(RECEIVED_SIGNAL[0], RECEIVED_SIGNAL[1])
pyplot.axis([0, MAX_DURATION, -1, 2])
pyplot.show()
outputa.close()
outputb.close()
Transmit part :
import time
import sys
import RPi.GPIO as GPIO
import pprint
import pickle
button_on = "button_on.pkl"
with open(button_on, "rb") as f:
print pickle.load(f)
button_on.close()
Here I have an error :
Traceback (most recent call last):
print pickle.load(f)
File '/usr/lib/python2.7/pickle.py', line 1378, in load
return Unpickler(file).load()
File '/usr/lib/python2.7/pickle.py', line 858, in load
dispatch[key](self)
File '/usr/lib/python2.7/pickle.py', line 1138, in load_pop del self.stack[.1]
IndexError: list assignment index out of range
Related
I am trying to loop this function over here to retrieve vaccine alerts via WhatsApp so it constantly monitors the server when I start the script. I tried using the while True: command, but this error kept occuring - how cld i fix this?
Traceback (most recent call last):
File "/Users/ragz/cowin.py", line 70, in <module>
vaccine_check()
File "/Users/ragz/cowin.py", line 35, in vaccine_check
json_output = json.dumps(available_centers, indent=4)
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/__init__.py", line 234, in dumps
return cls(
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 201, in encode
chunks = list(chunks)
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 438, in _iterencode
o = _default(o)
File "/usr/local/Cellar/python#3.9/3.9.4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type HTTPError is not JSON serializable
If anyone needs it, heres the code -
from cowin_api import CoWinAPI
import json
import datetime
import numpy as np
import os
from twilio.rest import Client
import selenium
from selenium import webdriver
import time
import io
import requests
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.webdriver.common.keys import Keys
from threading import Thread
state_id = '21'
district_id = '395'
min_age_limit = 18
time = datetime.datetime.now()
cowin = CoWinAPI()
# here im getting the centers and the vaccines
def vaccine_check():
try:
available_centers = cowin.get_availability_by_district(district_id)
#outputing it to a json file and bringing it back
json_output = json.dumps(available_centers, indent=4)
f = open(f'tests/vaccinecheck[{time.strftime("%b %d %Y %H|%M")}].json', 'w')
f.write(json_output)
f.close()
with open(f.name) as file:
data = json.load(file)
n = np.arange(100)
for x in np.nditer(n):
if data["centers"][x]["sessions"][0]["min_age_limit"] == 45:
print('')
else:
print(f'[{time.strftime("%b %d %Y %H:%M")}]', data["centers"][x]["name"], '-- vaccines:', data["centers"][x]["sessions"][0]['available_capacity'], '-- age-limit:', data["centers"][x]["sessions"][0]["min_age_limit"])
if data["centers"][x]["sessions"][0]["available_capacity"] >= 1:
twilio_send()
except IndexError: # catch the error
pass # pass will basically ignore it
def twilio_send():
client = Client()
from_whatsapp_number='whatsapp:twilio api demo num'
to_whatsapp_number='whatsapp:my phone num'
client.messages.create(body='vaccine available - book now!',
from_=from_whatsapp_number,
to=to_whatsapp_number)
while True:
vaccine_check()
I have a program that writes serial data to the text file. I want to check for specific card UIDs in the text file by reading the file at first, if there is already a card UID I want to skip the serial write step (serial write 0), if there isn't that card UID I will go ahead and serial write 1.
In order to check for card UIDs I have employed next command, please have a look at my code.
import threading
import serial
import sys
import io
import codecs
import queue
from pynput import keyboard
with io.open("uid.txt", "w", encoding="utf-8") as b:
b.write("")
q = queue.Queue()
ser = serial.Serial('COM4', baudrate = 9600, timeout = 5)
class SerialReaderThread(threading.Thread):
def run(self):
while True:
output = ser.readline().decode('utf-8')
print(output)
q.put(output)
class FileWriting(threading.Thread):
def run(self):
while True:
output = q.get()
with io.open("uid.txt", "r+", encoding="utf-8") as input:
for line in input:
if line.startswith("Card UID: "):
s = (next(input))
if line.startswith(s): ***
ser.write(b'0\r\n')
else:
ser.write(b'1\r\n')
with io.open("uid.txt", "a+", encoding="utf-8") as f:
f.write(output)
serial_thread = SerialReaderThread()
file_thread=FileWriting()
serial_thread.start()
file_thread.start()
serial_thread.join()
file_thread.join()
FileWriting thread is what I need help with. Again I want to first read the text file (which initially will be empty as it is created) and check for lines with card UID and look if there already is that specific card UID in the file if there is write 0 if there isn't write 1 in serial.
However running this code gives me an error:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\project\fff.py", line 36, in run
s = (next(input))
StopIteration
Since you re-create the uid.txt file empty each time you run your program, you don't need a file to hold the information. Just use a set instead:
ser = serial.Serial('COM4', baudrate = 9600, timeout = 5)
class SerialReaderThread(threading.Thread):
def run(self):
uids = set()
while True:
output = ser.readline().decode('utf-8')
print(output)
response = b'0' if output in uids else b'1'
ser.write(response + b'\r\n')
uids.add(output)
serial_thread = SerialReaderThread()
serial_thread.start()
serial_thread.join()
I am trying to set up a raspberry pi which measures the temperature and humidity in my room via a DHT22 sensor. I found a tutorial on youtube where the scripts and everything else is uploaded, but the python script won't work... I am new to python and I really don't know what to do now. I already searched for a solution, especially here on stackoverflow, but I didn't find anything working for me.
The error message looks like this:
python Temperature_Server_DHT.py
Traceback (most recent call last):
File "Temperature_Server_DHT.py", line 49, in <module>
SensorInforations = sensorCheckIfRegistered(Device_ID)
File "Temperature_Server_DHT.py", line 37, in sensorCheckIfRegistered
SensorData = json.loads(data)
File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
And my python script contains the following:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# import sys module
import sys
import json
import urllib
import time
import socket
import Adafruit_DHT
#Conf
BaseURL= "http://127.0.0.1/php/Backend.php"
NameSensor= "DHT22"
#
sensor = Adafruit_DHT.DHT22
ip = [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] [:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)$
hostname = socket.gethostname()
def insertTempdata(TSensor_ID, Temperature, Humidity):
urllib.urlopen(BaseURL + "?Call=AddTempData&TSensor_ID=" + "\"" + TSensor_ID + "\"" + "&Temperature="+ Temperature + "&Humidity=" + Humidity)
def deviceCheckIfRegistered(IP, Hostname):
DeviceID = urllib.urlopen(BaseURL + "?Call=getDeviceID&IP=" + IP + "&Hostname=" + Hostname ).read()
print (DeviceID)
if(DeviceID != "null"):
return DeviceID
else:
return ""
def sensorCheckIfRegistered(DeviceID):
url= BaseURL + "?Call=getRegisteredTSensors&Device_ID=" + DeviceID
data = urllib.urlopen(url).read()
print (data)
if(data != "null"):
SensorData = json.loads(data)
return SensorData
else:
return ""
def readDHTSensors(TSensor_ID, GPIO):
humidity, temperature = Adafruit_DHT.read_retry(sensor, GPIO)
print 'Temperature: {0:0.1f}*C Humidity: {1:0.1f}%'.format(temperature,humidity)
insertTempdata(TSensor_ID, str(temperature), str(humidity))
if __name__ == '__main__':
Device_ID = deviceCheckIfRegistered(ip, hostname)
SensorInforations = sensorCheckIfRegistered(Device_ID)
if(Device_ID != "" and SensorInforations != ""):
try:
while True:
for element in SensorInforations:
if(str(element['Sensor']) == NameSensor):
readDHTSensors(element['TSensor_ID'], element['GPIO'])
time.sleep(1800)
except (KeyboardInterrupt, SystemExit):
# quit python script
print("Killed")
sys.exit(0)
else:
print("Device not registered")
sys.exit(0)
I hope that you can finally help me, if you need anything else from me just tell me!
In this script I am taking the temperature from a DHT11 sensor and parsing the data that another script can read. Everything works except for writing the file to another pc using the path I placed in the f = open part of the script below. Everything works great except that the file doesn't get written or saved.
Any Help?
#!/usr/bin/env python
# encoding: utf-8
import sys
import time
import dht11
import RPi.GPIO as GPIO
#define GPIO 14 as DHT11 data pin
Temp_sensor=14
def main():
# Main program block
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers
instance = dht11.DHT11(pin = Temp_sensor)
while True:
#get DHT11 sensor value
result = instance.read()
temp = '{:.0f}'.format(result.temperature * 1.8 + 32)+"°"
# The path to send the txt file to and save is /10.1.1.28/c$/Temperature_RETR/kvoa_temp.txt
if result.is_valid():
print temp
f = open('\\10.1.1.28\c$\Temperature_RETR\new_temp.txt','w')
#f = open('/home/pi/Desktop/new_temp.txt','w')
y = temp
z = str(y)
f.write(z)
f.close()
time.sleep(60) # 60 second delay
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
I'm trying to get my RPi to send temp data to Xively and I'm having a horrible time getting my code to work. This is the latest reponse I get when I run the python script...
Traceback (most recent call last):
File "xively1.py", line 11, in <module>
import xively # for Xively
File "/home/pi/xively/xively.py", line 11, in <module>
FEED_ID = os.environ["736915202"]
File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: '736915202'
Can someone explain to me what this means and what I need to do to correct? Thanks.
#!/usr/bin/env python
# This program reads two DS18B20 1-wire temperature sensors and sends the values to
# Xively https://xively.com/feeds/360495937
# tempF[0] is the reading from the outdoor tempersture sensor '28-0000059f6ece'
# tempF[1] is the reading from the indoor temperature sensor '28-0000059fa9ce'
outdoor = 0
indoor = 1
import xively # for Xively
import time
import datetime
import os # for 1-wire
import glob # for 1-wire
def read_temp_raw(): #a function that grabs the raw temperatures data from the sensors
f_1 = open(device_file[0], 'r') # first DS18B20
lines_1 = f_1.readlines()
f_1.close()
f_2 = open(device_file[1], 'r') # second DS18B20
lines_2 = f_2.readlines()
f_2.close()
return lines_1 + lines_2
def read_temp(): #a function that checks that the connections were good
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES' or lines[2].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t='), lines[3].find('t=')
tempC = float(lines[1][equals_pos[0]+2:])/1000, float(lines[3] [equals_pos[1]+2:])/1000
tempF = round(tempC[0] * 9.0 / 5.0 + 32.0,1), round(tempC[1] * 9.0 / 5.0 + 32.0,1)
return tempF
def send_to_Xively(TempF):
XIVELY_FEED_ID = "736915202"
XIVELY_API_KEY = "QA6mqStQIqCFLOXtA4tzxiFpv8cqHNaYr1MFjRZdrphGwxYN"
#def send_to_Xively(TempF):
now = datetime.datetime.utcnow()
try:
print "Sending to Xively...",
xivelyapi = xively.XivelyAPIClient(XIVELY_API_KEY)
xivelyfeed = xivelyapi.feeds.get(XIVELY_FEED_ID)
xivelyfeed.datastreams = [
xively.Datastream(id='temp0', current_value=round(TempF[outdoor],1), at=now),
xively.Datastream(id='temp1', current_value=round(TempF[indoor],1), at=now)
]
xivelyfeed.update()
print "OK"
except requests.HTTPError as e:
print "HTTPError({0}): {1}".format(e.errno, e.strerror)
# this part for the 1-wire DS18S20
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
#set up the locations of the sensors in the system
device_folder = glob.glob('/sys/bus/w1/devices/28*')
device_file = [device_folder[0] + '/w1_slave', device_folder[1] + '/w1_slave']
# main program
TempF = read_temp()
send_to_Xively(TempF)
The xively module is expecting the environment variable "736915202" to be set. It's not, so it's throwing an exception.
That seems like a very strange environment variable to have set, though. Is /home/pi/xively/xively.py a third-party module, or did you write it? If you wrote that file, but you expected calling import xively to import a third-party module, you should rename /home/pi/xively/xively.py to something else, and that will probably fix your problem.
public class AnimalPrinter
{
public void printDog()
{
System.out.println("dog");
}
public void printCat()
{
System.out.println("cat");
}
/* constructors not shown */
}