サーバーとラズベリーパイはソケット通信で接続されています。データ送信側がサーバー、データ受信側をラズベリーパイとして、サーバー上のプログラムの中でif文でa=1ならラズベリーパイ上にデータ1を出力、a=2のときラズベリーパイ上にデータ2を出力、、といったことを行いたいのですが、
python
1# -*- Coding: utf-8 -*- 2import serial 3import time 4import socket 5import requests 6import argparse 7import json 8import cv2 9import subprocess 10 11import pandas as pd 12import numpy as np 13from scipy import signal 14import pywt 15import threading 16 17import picamera 18import picamera.array 19with picamera.PiCamera() as camera: 20 camera.resolution = (400,300) 21 camera.start_preview() 22 camera.capture('test.jpg') 23 24import matplotlib 25matplotlib.rcParams['backend']='TkAgg' 26import matplotlib.pyplot as plt 27from PIL import Image 28from io import BytesIO 29import errno 30 31import collections as cl 32import datetime 33from timeout_decorator import timeout, TimeoutError 34 35subscription_key = "key添付予定" 36assert subscription_key 37 38 39 40image_path = "/home/pi/test.jpg" 41 42parser = argparse.ArgumentParser() 43parser.add_argument('--ip_addr', help="Put the client's ip address here") 44args = parser.parse_args() 45 46 47connorclo=0 48 49def main(): 50 RR=[] 51 sin=[] 52 gpio_seri = serial.Serial('/dev/ttyUSB0', 115200, timeout=1) 53 dt=1 54 fs = 1.0/dt 55 56 cnt = 0 57 58 59 senddic={} 60 print("START") 61 t=1 62 senddic={} 63 print("START") 64 t=1 65 gpsla=gpsla1=0.0 66 gpslo=gpslo1=0.0 67 while True: 68 69 70 71 bio_data = gpio_seri.readline().rstrip().decode('unicode-escape')+","+str(gpsla)+","+str(gpsla) 72 73 74 bd=bio_data.split(",") 75 if len(bd)>17: 76 if bd[15] == '': 77 bd[15] = 60 78 elif bd[15].isdecimal() == False: 79 bd[15] = 60 80 else: 81 sin.append(int(bd[15])) 82 if int(bd[15])>0: 83 r = 60/float(bd[15]) 84 RR.append(r) 85 86 87 cnt +=1 88 if cnt % 10 ==0: 89 print(cnt) 90 91 92 if(len(RR)>=1024): 93 #mae ha 5 94 dt_now=datetime.datetime.now().strftime('%Y/%m/%d_%H:%M:%S') 95 print(dt_now) 96 print("ond: "+bd[0]+" sitsudo: "+bd[1]+" taikiatsu: "+bd[2]+" kido: "+bd[3]+" dkenti: "+ bd[4]) 97 print("kasokux: "+bd[5]+" ky: "+bd[6]+" kz: "+bd[7]+" kkx: "+bd[8]+" kky: "+bd[9]+" kkz: "+bd[10]+" tizix: "+bd[11]+" tiziy: "+bd[12]+" tiziz: "+bd[13]) 98 print("taion: "+bd[14]+" sinpaku: "+bd[15]+" GSR: "+bd[16]) 99 print("heikinshinpaku", sum(sin)/len(sin),"RRheikin",sum(RR)/len(RR),int(len(RR))) 100 t1 = time.time() 101 s = pd.Series(RR) 102 #freq2, pow_dend=signal.periodogram(s, fs) 103 vlf = 0.04 104 lf = 0.15 105 hf = 0.4 106 Fs = 250 107 dy=1.0/Fs 108 nq_f = fs/2.0 109 110 wavelet_type = 'cmor1.5-1.0' 111 wav = pywt.ContinuousWavelet(wavelet_type) 112 freqs = np.linspace(0.0001,nq_f,1024) 113 freqs_rate = freqs / fs 114 scales = 1 / freqs_rate 115 scales = scales[::-1] 116 frequencies_rate = pywt.scale2frequency(scale=scales, wavelet=wavelet_type) 117 118 frequencies = frequencies_rate / dt 119 120 cwtmatr, freqs_rate = pywt.cwt(s, scales, wavelet_type) 121 pow_den = (np.abs(cwtmatr)) 122 123 pow_den = pow_den[200] 124 lf_freq_band = (freqs_rate >= vlf) & (freqs_rate <= lf) 125 hf_freq_band = (freqs_rate >= lf) & (freqs_rate <= hf) 126 LF1 = np.trapz(pow_den[lf_freq_band], x=None, dx=dy) 127 HF1 = np.trapz(pow_den[hf_freq_band], x=None, dx=dy) 128 129 pow_den = (np.abs(cwtmatr)) 130 pow_den = pow_den[400] 131 #print(pow_den) 132 lf_freq_band = (freqs_rate >= vlf) & (freqs_rate <= lf) 133 hf_freq_band = (freqs_rate >= lf) & (freqs_rate <= hf) 134 LF2 = np.trapz(pow_den[lf_freq_band], x=None, dx=dy) 135 HF2 = np.trapz(pow_den[hf_freq_band], x=None, dx=dy) 136 137 pow_den = (np.abs(cwtmatr)) 138 pow_den = pow_den[600] 139 lf_freq_band = (freqs_rate >= vlf) & (freqs_rate <= lf) 140 hf_freq_band = (freqs_rate >= lf) & (freqs_rate <= hf) 141 LF3 = np.trapz(pow_den[lf_freq_band], x=None, dx=dy) 142 HF3 = np.trapz(pow_den[hf_freq_band], x=None, dx=dy) 143 144 pow_den = (np.abs(cwtmatr)) 145 pow_den = pow_den[800] 146 lf_freq_band = (freqs_rate >= vlf) & (freqs_rate <= lf) 147 hf_freq_band = (freqs_rate >= lf) & (freqs_rate <= hf) 148 LF4 = np.trapz(pow_den[lf_freq_band], x=None, dx=dy) 149 HF4 = np.trapz(pow_den[hf_freq_band], x=None, dx=dy) 150 151 pow_den = (np.abs(cwtmatr)) 152 pow_den = pow_den[1000] 153 lf_freq_band = (freqs_rate >= vlf) & (freqs_rate <= lf) 154 hf_freq_band = (freqs_rate >= lf) & (freqs_rate <= hf) 155 LF5 = np.trapz(pow_den[lf_freq_band], x=None, dx=dy) 156 HF5 = np.trapz(pow_den[hf_freq_band], x=None, dx=dy) 157 158 LF_HF = (np.float64(LF1+LF2+LF3+LF4+LF5) / (HF1+HF2+HF3+HF4+HF5)) * 5 159 print(LF_HF) 160 t2 = time.time() 161 elapsed_time = t2-t1 162 #print(elapsed_time) 163 164 bio_data=bio_data+","+str(LF_HF) 165 with socket.socket(socket.AF_INET,socket.SOCK_STREAM)as s: 166 data = socket.recv(2) 167 if(data==1): 168 subprocess.call("aplay 20211110_075611.wav", shell=True) 169 170 elif(data==2): 171 subprocess.call("aplay 20211110_075639.wav", shell=True) 172 173 elif(data==3): 174 subprocess.call("aplay 20211110_075718.wav", shell=True) 175 176 elif(data==4): 177 subprocess.call("aplay 20211110_075611.wav", shell=True) 178 179 elif(data==5): 180 subprocess.call("aplay 20211110_075611.wav", shell=True) 181 182 elif(data==6): 183 subprocess.call("aplay 20211110_075805.wav", shell=True) 184 185 else: 186 pass 187 188 with picamera.PiCamera() as camera: 189 camera.resolution = (400,300) 190 camera.capture('test.jpg') 191 image_data = open(image_path, "rb").read() 192 img = cv2.imread(image_path) 193 cv2.waitKey(1000) 194 headers = {'Ocp-Apim-Subscription-Key': subscription_key, 195 'Content-Type': 'application/octet-stream'} 196 params = {'visualFeatures': 'Description'} 197 try: 198 response = requests.post( 199 analyze_url, headers=headers, params=params, data=image_data) 200 except requests.exceptions.ConnectionError: 201 continue 202 #print(datetime.datetime.now()) 203 response.raise_for_status() 204 analysis = response.json()['description']['tags'] 205 jsonana=json.dumps(analysis).replace("\"","") 206 if connorclo==1: 207 jsonana1=json.dumps(analysis) 208 gpsthread3 = threading.Thread(target=socket_data, args=(bio_data, jsonana1)) 209 gpsthread3.daemon = True 210 gpsthread3.start() 211 212 dt_now=datetime.datetime.now().strftime('%Y/%m/%d_%H:%M:%S') 213 senddic["key"+str(t)] = {"nowtime":dt_now} 214 senddic["key"+str(t)].update({"bio_data":bio_data}) 215 senddic["key"+str(t)].update({"camera":jsonana}) 216 217 t+=1 218 print(connorclo) 219 print("b") 220 if(t==3): 221 json_data = json.dumps(senddic).replace("\\", "").replace("[","").replace("]","").replace(" ","") 222 223 file_path = "./sendata2.json" 224 with open(file_path, 'w') as f: 225 json.dump(json_data, f,ensure_ascii=False) 226 227 t=1 228 print("a") 229 sendic={} 230 print("wait") 231 232 if cv2.waitKey(1) & 0xFF == ord('q'): 233 break 234 cnt=0 235 del RR[:100] 236 cv2.destroyAllWindows() 237 238if __name__ == '__main__': 239 main() 240
上記のプログラムを実行時に、次の箇所について
python
1 with socket.socket(socket.AF_INET,socket.SOCK_STREAM)as s: 2 data = socket.recv(2) 3 if(data==1): 4 subprocess.call("aplay 20211110_075611.wav", shell=True) 5 6 elif(data==2): 7 subprocess.call("aplay 20211110_075639.wav", shell=True) 8 9 elif(data==3): 10 subprocess.call("aplay 20211110_075718.wav", shell=True) 11 12 elif(data==4): 13 subprocess.call("aplay 20211110_075611.wav", shell=True) 14 15 elif(data==5): 16 subprocess.call("aplay 20211110_075611.wav", shell=True) 17 18 elif(data==6): 19 subprocess.call("aplay 20211110_075805.wav", shell=True) 20 21 else: 22 pass
AttributeError: type object socket has no attribute 'recv'
というエラーが発生したため、どのようにプログラムを修正するべきか教えていただけないでしょうか。
そのサーバなるものと、ラズパイというのはどういうふうに接続されてるんでしょうか。
また、ラズパイじゃなく、ふつうのPCであればその方法はわかるんでしょうか。
あまりに説明不足すぎて答えようがないです
「指定」は誰がどのようにするのですか、なんてことも不明です。
送信すること自体は多分とても簡単なことになるはずですが、何をどうしたいかが説明されていないので例を示すことはできません。
ご意見ありがとうございます。この度は、私の説明不足により大変申し訳ございませんでした。いただいた意見をもとに質問内容の追記をさせていただきます。
> ソケット通信で接続されています。
接続できているのなら、一方でsendしてもう一方でrecvすればよいのではないでしょうか?
'Python socket'あたりで検索すればいろいろ例が見つかると思いますが、それでは不明ななにかがありますか?
ご意見ありがとうございます。実際にプログラムを動作させてみたのですが、
AttributeError: type object socket has no attribute 'recv'
とエラーが表示されてしまいました。
こちらのエラーについて検索をしてみたのですが、エラーが発生する原因がわからないため、なぜこのようなエラーが表示されるか知っていることがございましたら、申し訳ないのですが教えていただけないでしょうか。
質問文にそれを書きましょう
ここで長々と書いてますが、あなたに聞きたいのはただひとつ、
質門はなんでしょうか
すみません、超能力スキルが足りなくて、ソースコードなしに出たエラーだけ示されても私には解決できそうにありません。
回答1件
あなたの回答
tips
プレビュー