박권수

Merge branch 'master' into server

Showing 163 changed files with 8857 additions and 37 deletions
1 +{
2 + // IntelliSense를 사용하여 가능한 특성에 대해 알아보세요.
3 + // 기존 특성에 대한 설명을 보려면 가리킵니다.
4 + // 자세한 내용을 보려면 https://go.microsoft.com/fwlink/?linkid=830387을(를) 방문하세요.
5 + "version": "0.2.0",
6 + "configurations": [
7 + {
8 + "name": "flutter_application_1",
9 + "cwd": "frontend\\flutter_application_1",
10 + "request": "launch",
11 + "type": "dart"
12 + }
13 + ]
14 +}
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "dart.previewFlutterUiGuides": true
3 +}
...\ No newline at end of file ...\ No newline at end of file
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
17 각 개발자의 작업사항을 보시려면 개발자의 이름을 클릭하세요. 17 각 개발자의 작업사항을 보시려면 개발자의 이름을 클릭하세요.
18 18
19 - [고원빈 : 프론트엔드, Native Android Application 개발](http://khuhub.khu.ac.kr/2021-1-capstone-design1/RIT_Project1/tree/frontend/frontend) 19 - [고원빈 : 프론트엔드, Native Android Application 개발](http://khuhub.khu.ac.kr/2021-1-capstone-design1/RIT_Project1/tree/frontend/frontend)
20 -1. Framework : Flutter 1.6.2 20 +1. Framework : Flutter 1.22.6
21 2. 언어 : Dart 21 2. 언어 : Dart
22 3. 주요 통신 : HTTP Request, Response(Server와 통신) 22 3. 주요 통신 : HTTP Request, Response(Server와 통신)
23 23
......
1 +# 스마트 약병 IoT FRONTEND 개발
2 +## 지도교수
3 ++ 유인태 교수님
4 +
5 +## 팀원
6 ++ 2016104102 컴퓨터공학과 고원빈
7 +
8 +
9 +## 일정
10 ++ 2021-04-27 : Flutter 앱 생성 및 개발 환경 설정
11 ++ 2021-04-27 : 시작화면 router 생성
12 +
13 +### 2021-04-28
14 ++ flutter version 변경 작업
15 +
16 +### 2021-04-29
17 ++ Main 화면 작업 완료
18 +![로그인_화면](/uploads/d12f35739c9263e37009cc9b3bbe06d4/로그인_화면.PNG)
19 ++ 로그인 페이지 작업 완료
20 +![222](/uploads/8cc867cd159e28c04ff2a09e3a42c2d6/222.PNG)
21 +
22 +
23 +### 2021-05-09
24 ++ Appbar 기능 구현
25 +appbar 관련 디자인은 추후 구현 예정
26 +
27 +### 2021-05-10
28 ++ Appbar 디자인 변경 및 Navgation Bar 구현
29 ++ Setting은 별도의 페이지로 구성
30 +
31 +### 2021-05-11
32 ++ Inside Information 화면 구성
33 +<img src = "https://user-images.githubusercontent.com/56704722/117849827-aadc6400-b2bf-11eb-8cdb-2c7f37833d01.png" width="400">
34 ++ Outside Information 화면 구성
35 +<img src ="https://user-images.githubusercontent.com/56704722/117849959-cd6e7d00-b2bf-11eb-86b7-bc97356c7665.png" width="400">
36 ++ Setting Page 화면 구성
37 +<img src = "https://user-images.githubusercontent.com/56704722/117850038-e24b1080-b2bf-11eb-8dcd-5cb96a9056e0.png" width="400">
38 +
39 +
40 +### 2021-05-13
41 ++ flutter notification 추가 알람 설정 완료
42 ++ datetime picker widget을 이용하여 시간 선택 구현 예정
43 ++ 알람 설정을 위한 Android Mainfest 설정 , 사용자 권한 요구
44 +
45 +### 2021-05-14
46 ++ datetime picker 를 이용하여 알람 설정 완료
47 ++ 현재 알람 페이지와 알람 수정 페이지가 같은 곳에 위치 이에 따라 보이는 데이터만 존재하고 수정 여부를 묻는 것을 만들지 고민중
48 +
49 +### 2021-05-15
50 ++ 회원 정보 수정 Page 구현
51 ++ API 연동 중에 추가로 개발 예정
52 ++ build용 파일 구현
53 +
54 +### 2021-05-17
55 ++ server test 완료
56 +
57 +### 2021-05-18
58 ++ 회원 가입 SERVER 연동
59 +
60 +### 2021-05-19
61 ++ Login 연동
62 ++ 약병 등록 ,허브 등록 구현
63 +
64 +### 2021-05-20
65 ++ 시나리오 수정
66 +
67 +### 2021-05-21
68 ++ 약병 ,허브 리스트 출력 구현
69 +
70 +### 2021-05-22
71 ++ 약병 검색 기능 구현 중
72 +
73 +### 2021-05-23
74 ++ 로그인 하여 메인페이지 과정 구현 완료
75 ++ 폴더 정리
76 +
77 +
78 +### 2021-05-24
79 +회원 가입 --> 허브 등록 --> 약병 등록 -->로그인 페이지로
80 +로그인 --> 허브 리스트 --> 약병 리스트 --> 메인 페이지
81 ++ 시나리오 수정 완료
82 ++ 메인 페이지 데이터 출력 완료
83 +
84 +
85 +### 2021-05-25
86 ++ 로그인 권한 문제 해결
87 +
88 +### 2021-05-26
89 ++ future buillder 변경
90 +
91 +### 2021-05-27
92 ++ app 뒤로가기 설정 변경
93 +
94 +### 2021-05-29
95 ++ 약병 리스트 ui 변경
96 ++ DashBoard 새로고침
97 +
98 +### 2021-05-30
99 ++ Sqlite 생성
100 +
101 +### 2021-06-01
102 ++ datetime 형식 한국 시간으로 변경
103 +
104 +### 2021-06-02
105 ++ 약병 , 허브 추가 제거 관리 페이지 구현
1 +SERVER_URL=http://192.168.0.3:4717/api/
...\ No newline at end of file ...\ No newline at end of file
1 +# Miscellaneous
2 +*.class
3 +*.log
4 +*.pyc
5 +*.swp
6 +.DS_Store
7 +.atom/
8 +.buildlog/
9 +.history
10 +.svn/
11 +
12 +# IntelliJ related
13 +*.iml
14 +*.ipr
15 +*.iws
16 +.idea/
17 +
18 +# The .vscode folder contains launch configuration and tasks you configure in
19 +# VS Code which you may wish to be included in version control, so this line
20 +# is commented out by default.
21 +#.vscode/
22 +
23 +# Flutter/Dart/Pub related
24 +**/doc/api/
25 +**/ios/Flutter/.last_build_id
26 +.dart_tool/
27 +.flutter-plugins
28 +.flutter-plugins-dependencies
29 +.packages
30 +.pub-cache/
31 +.pub/
32 +/build/
33 +
34 +# Web related
35 +lib/generated_plugin_registrant.dart
36 +
37 +# Symbolication related
38 +app.*.symbols
39 +
40 +# Obfuscation related
41 +app.*.map.json
1 +# This file tracks properties of this Flutter project.
2 +# Used by Flutter tool to assess capabilities and perform upgrades etc.
3 +#
4 +# This file should be version controlled and should not be manually edited.
5 +
6 +version:
7 + revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
8 + channel: stable
9 +
10 +project_type: app
1 +# flutter_application_1
2 +
3 +A new Flutter project.
4 +
5 +## Getting Started
6 +
7 +This project is a starting point for a Flutter application.
8 +
9 +A few resources to get you started if this is your first Flutter project:
10 +
11 +- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab)
12 +- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook)
13 +
14 +For help getting started with Flutter, view our
15 +[online documentation](https://flutter.dev/docs), which offers tutorials,
16 +samples, guidance on mobile development, and a full API reference.
1 +gradle-wrapper.jar
2 +/.gradle
3 +/captures/
4 +/gradlew
5 +/gradlew.bat
6 +/local.properties
7 +GeneratedPluginRegistrant.java
8 +
9 +# Remember to never publicly share your keystore.
10 +# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app
11 +key.properties
1 +def localProperties = new Properties()
2 +def localPropertiesFile = rootProject.file('local.properties')
3 +if (localPropertiesFile.exists()) {
4 + localPropertiesFile.withReader('UTF-8') { reader ->
5 + localProperties.load(reader)
6 + }
7 +}
8 +
9 +def flutterRoot = localProperties.getProperty('flutter.sdk')
10 +if (flutterRoot == null) {
11 + throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
12 +}
13 +
14 +def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
15 +if (flutterVersionCode == null) {
16 + flutterVersionCode = '1'
17 +}
18 +
19 +def flutterVersionName = localProperties.getProperty('flutter.versionName')
20 +if (flutterVersionName == null) {
21 + flutterVersionName = '1.0'
22 +}
23 +
24 +apply plugin: 'com.android.application'
25 +apply plugin: 'kotlin-android'
26 +apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
27 +
28 +android {
29 + compileSdkVersion 29
30 +
31 + sourceSets {
32 + main.java.srcDirs += 'src/main/kotlin'
33 + }
34 +
35 + lintOptions {
36 + disable 'InvalidPackage'
37 + }
38 +
39 + defaultConfig {
40 + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
41 + applicationId "com.example.Smart_Medicine_Box"
42 + minSdkVersion 19
43 + targetSdkVersion 29
44 + versionCode flutterVersionCode.toInteger()
45 + versionName flutterVersionName
46 + }
47 +
48 + buildTypes {
49 + release {
50 + // TODO: Add your own signing config for the release build.
51 + // Signing with the debug keys for now, so `flutter run --release` works.
52 + signingConfig signingConfigs.debug
53 + }
54 + }
55 +}
56 +
57 +flutter {
58 + source '../..'
59 +}
60 +
61 +dependencies {
62 + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
63 +}
1 +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
2 + package="com.example.flutter_application_1">
3 + <!-- Flutter needs it to communicate with the running application
4 + to allow setting breakpoints, to provide hot reload, etc.
5 + -->
6 + <uses-permission android:name="android.permission.INTERNET"/>
7 +</manifest>
1 +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
2 + package="com.example.flutter_application_1">
3 +
4 + <!-- io.flutter.app.FlutterApplication is an android.app.Application that
5 + calls FlutterMain.startInitialization(this); in its onCreate method.
6 + In most cases you can leave this as-is, but you if you want to provide
7 + additional functionality it is fine to subclass or reimplement
8 + FlutterApplication and put your custom class here. -->
9 + <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
10 + <uses-permission android:name="android.permission.VIBRATE" />
11 + <uses-permission android:name="android.permission.BLUETOOTH" />
12 + <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
13 + <uses-permission android:name="android.permission.INTERNET"/>
14 + <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
15 + <application
16 + android:name="io.flutter.app.FlutterApplication"
17 + android:label="Smart_Medicine_Box"
18 + android:icon="@mipmap/ic_launcher">
19 + <activity
20 + android:name=".MainActivity"
21 + android:launchMode="singleTop"
22 + android:theme="@style/LaunchTheme"
23 + android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
24 + android:hardwareAccelerated="true"
25 + android:windowSoftInputMode="adjustResize">
26 + <!-- Specifies an Android theme to apply to this Activity as soon as
27 + the Android process has started. This theme is visible to the user
28 + while the Flutter UI initializes. After that, this theme continues
29 + to determine the Window background behind the Flutter UI. -->
30 + <meta-data
31 + android:name="io.flutter.embedding.android.NormalTheme"
32 + android:resource="@style/NormalTheme"
33 + />
34 + <!-- Displays an Android View that continues showing the launch screen
35 + Drawable until Flutter paints its first frame, then this splash
36 + screen fades out. A splash screen is useful to avoid any visual
37 + gap between the end of Android's launch screen and the painting of
38 + Flutter's first frame. -->
39 + <meta-data
40 + android:name="io.flutter.embedding.android.SplashScreenDrawable"
41 + android:resource="@drawable/launch_background"
42 + />
43 + <intent-filter>
44 + <action android:name="android.intent.action.MAIN"/>
45 + <category android:name="android.intent.category.LAUNCHER"/>
46 + </intent-filter>
47 +
48 +
49 + </activity>
50 + <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
51 + <intent-filter>
52 + <action android:name="android.intent.action.BOOT_COMPLETED"/>
53 + <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
54 + </intent-filter>
55 + </receiver>
56 + <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
57 +
58 + <!-- Don't delete the meta-data below.
59 + This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
60 + <meta-data
61 + android:name="flutterEmbedding"
62 + android:value="2" />
63 + </application>
64 +</manifest>
1 +package com.example.flutter_application_1
2 +
3 +import io.flutter.embedding.android.FlutterActivity
4 +
5 +class MainActivity: FlutterActivity() {
6 +}
1 +<?xml version="1.0" encoding="utf-8"?>
2 +<!-- Modify this file to customize your launch splash screen -->
3 +<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
4 + <item android:drawable="@android:color/white" />
5 +
6 + <!-- You can insert your own image assets here -->
7 + <!-- <item>
8 + <bitmap
9 + android:gravity="center"
10 + android:src="@mipmap/launch_image" />
11 + </item> -->
12 +</layer-list>
1 +<?xml version="1.0" encoding="utf-8"?>
2 +<resources>
3 + <!-- Theme applied to the Android Window while the process is starting -->
4 + <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
5 + <!-- Show a splash screen on the activity. Automatically removed when
6 + Flutter draws its first frame -->
7 + <item name="android:windowBackground">@drawable/launch_background</item>
8 + </style>
9 + <!-- Theme applied to the Android Window as soon as the process has started.
10 + This theme determines the color of the Android Window while your
11 + Flutter UI initializes, as well as behind your Flutter UI while its
12 + running.
13 +
14 + This Theme is only used starting with V2 of Flutter's Android embedding. -->
15 + <style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
16 + <item name="android:windowBackground">@android:color/white</item>
17 + </style>
18 +</resources>
1 +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
2 + package="com.example.flutter_application_1">
3 + <!-- Flutter needs it to communicate with the running application
4 + to allow setting breakpoints, to provide hot reload, etc.
5 + -->
6 + <uses-permission android:name="android.permission.INTERNET"/>
7 +</manifest>
1 +buildscript {
2 + ext.kotlin_version = '1.3.50'
3 + repositories {
4 + google()
5 + jcenter()
6 + }
7 +
8 + dependencies {
9 + classpath 'com.android.tools.build:gradle:3.5.0'
10 + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
11 + }
12 +}
13 +
14 +allprojects {
15 + repositories {
16 + google()
17 + jcenter()
18 + }
19 +}
20 +
21 +rootProject.buildDir = '../build'
22 +subprojects {
23 + project.buildDir = "${rootProject.buildDir}/${project.name}"
24 +}
25 +subprojects {
26 + project.evaluationDependsOn(':app')
27 +}
28 +
29 +task clean(type: Delete) {
30 + delete rootProject.buildDir
31 +}
1 +org.gradle.jvmargs=-Xmx1536M
2 +android.useAndroidX=true
3 +android.enableJetifier=true
4 +android.enableR8=true
1 +#Fri Jun 23 08:50:38 CEST 2017
2 +distributionBase=GRADLE_USER_HOME
3 +distributionPath=wrapper/dists
4 +zipStoreBase=GRADLE_USER_HOME
5 +zipStorePath=wrapper/dists
6 +distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip
1 +include ':app'
2 +
3 +def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
4 +def properties = new Properties()
5 +
6 +assert localPropertiesFile.exists()
7 +localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
8 +
9 +def flutterSdkPath = properties.getProperty("flutter.sdk")
10 +assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
11 +apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
1 +*.mode1v3
2 +*.mode2v3
3 +*.moved-aside
4 +*.pbxuser
5 +*.perspectivev3
6 +**/*sync/
7 +.sconsign.dblite
8 +.tags*
9 +**/.vagrant/
10 +**/DerivedData/
11 +Icon?
12 +**/Pods/
13 +**/.symlinks/
14 +profile
15 +xcuserdata
16 +**/.generated/
17 +Flutter/App.framework
18 +Flutter/Flutter.framework
19 +Flutter/Flutter.podspec
20 +Flutter/Generated.xcconfig
21 +Flutter/app.flx
22 +Flutter/app.zip
23 +Flutter/flutter_assets/
24 +Flutter/flutter_export_environment.sh
25 +ServiceDefinitions.json
26 +Runner/GeneratedPluginRegistrant.*
27 +
28 +# Exceptions to above rules.
29 +!default.mode1v3
30 +!default.mode2v3
31 +!default.pbxuser
32 +!default.perspectivev3
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 +<plist version="1.0">
4 +<dict>
5 + <key>CFBundleDevelopmentRegion</key>
6 + <string>$(DEVELOPMENT_LANGUAGE)</string>
7 + <key>CFBundleExecutable</key>
8 + <string>App</string>
9 + <key>CFBundleIdentifier</key>
10 + <string>io.flutter.flutter.app</string>
11 + <key>CFBundleInfoDictionaryVersion</key>
12 + <string>6.0</string>
13 + <key>CFBundleName</key>
14 + <string>App</string>
15 + <key>CFBundlePackageType</key>
16 + <string>FMWK</string>
17 + <key>CFBundleShortVersionString</key>
18 + <string>1.0</string>
19 + <key>CFBundleSignature</key>
20 + <string>????</string>
21 + <key>CFBundleVersion</key>
22 + <string>1.0</string>
23 + <key>MinimumOSVersion</key>
24 + <string>8.0</string>
25 +</dict>
26 +</plist>
1 +// !$*UTF8*$!
2 +{
3 + archiveVersion = 1;
4 + classes = {
5 + };
6 + objectVersion = 46;
7 + objects = {
8 +
9 +/* Begin PBXBuildFile section */
10 + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
11 + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
12 + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
13 + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
14 + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
15 + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
16 +/* End PBXBuildFile section */
17 +
18 +/* Begin PBXCopyFilesBuildPhase section */
19 + 9705A1C41CF9048500538489 /* Embed Frameworks */ = {
20 + isa = PBXCopyFilesBuildPhase;
21 + buildActionMask = 2147483647;
22 + dstPath = "";
23 + dstSubfolderSpec = 10;
24 + files = (
25 + );
26 + name = "Embed Frameworks";
27 + runOnlyForDeploymentPostprocessing = 0;
28 + };
29 +/* End PBXCopyFilesBuildPhase section */
30 +
31 +/* Begin PBXFileReference section */
32 + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
33 + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
34 + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
35 + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
36 + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
37 + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
38 + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
39 + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
40 + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
41 + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
42 + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
43 + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
44 + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
45 +/* End PBXFileReference section */
46 +
47 +/* Begin PBXFrameworksBuildPhase section */
48 + 97C146EB1CF9000F007C117D /* Frameworks */ = {
49 + isa = PBXFrameworksBuildPhase;
50 + buildActionMask = 2147483647;
51 + files = (
52 + );
53 + runOnlyForDeploymentPostprocessing = 0;
54 + };
55 +/* End PBXFrameworksBuildPhase section */
56 +
57 +/* Begin PBXGroup section */
58 + 9740EEB11CF90186004384FC /* Flutter */ = {
59 + isa = PBXGroup;
60 + children = (
61 + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
62 + 9740EEB21CF90195004384FC /* Debug.xcconfig */,
63 + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
64 + 9740EEB31CF90195004384FC /* Generated.xcconfig */,
65 + );
66 + name = Flutter;
67 + sourceTree = "<group>";
68 + };
69 + 97C146E51CF9000F007C117D = {
70 + isa = PBXGroup;
71 + children = (
72 + 9740EEB11CF90186004384FC /* Flutter */,
73 + 97C146F01CF9000F007C117D /* Runner */,
74 + 97C146EF1CF9000F007C117D /* Products */,
75 + );
76 + sourceTree = "<group>";
77 + };
78 + 97C146EF1CF9000F007C117D /* Products */ = {
79 + isa = PBXGroup;
80 + children = (
81 + 97C146EE1CF9000F007C117D /* Runner.app */,
82 + );
83 + name = Products;
84 + sourceTree = "<group>";
85 + };
86 + 97C146F01CF9000F007C117D /* Runner */ = {
87 + isa = PBXGroup;
88 + children = (
89 + 97C146FA1CF9000F007C117D /* Main.storyboard */,
90 + 97C146FD1CF9000F007C117D /* Assets.xcassets */,
91 + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
92 + 97C147021CF9000F007C117D /* Info.plist */,
93 + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
94 + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
95 + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
96 + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
97 + );
98 + path = Runner;
99 + sourceTree = "<group>";
100 + };
101 +/* End PBXGroup section */
102 +
103 +/* Begin PBXNativeTarget section */
104 + 97C146ED1CF9000F007C117D /* Runner */ = {
105 + isa = PBXNativeTarget;
106 + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
107 + buildPhases = (
108 + 9740EEB61CF901F6004384FC /* Run Script */,
109 + 97C146EA1CF9000F007C117D /* Sources */,
110 + 97C146EB1CF9000F007C117D /* Frameworks */,
111 + 97C146EC1CF9000F007C117D /* Resources */,
112 + 9705A1C41CF9048500538489 /* Embed Frameworks */,
113 + 3B06AD1E1E4923F5004D2608 /* Thin Binary */,
114 + );
115 + buildRules = (
116 + );
117 + dependencies = (
118 + );
119 + name = Runner;
120 + productName = Runner;
121 + productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
122 + productType = "com.apple.product-type.application";
123 + };
124 +/* End PBXNativeTarget section */
125 +
126 +/* Begin PBXProject section */
127 + 97C146E61CF9000F007C117D /* Project object */ = {
128 + isa = PBXProject;
129 + attributes = {
130 + LastUpgradeCheck = 1020;
131 + ORGANIZATIONNAME = "";
132 + TargetAttributes = {
133 + 97C146ED1CF9000F007C117D = {
134 + CreatedOnToolsVersion = 7.3.1;
135 + LastSwiftMigration = 1100;
136 + };
137 + };
138 + };
139 + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
140 + compatibilityVersion = "Xcode 9.3";
141 + developmentRegion = en;
142 + hasScannedForEncodings = 0;
143 + knownRegions = (
144 + en,
145 + Base,
146 + );
147 + mainGroup = 97C146E51CF9000F007C117D;
148 + productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
149 + projectDirPath = "";
150 + projectRoot = "";
151 + targets = (
152 + 97C146ED1CF9000F007C117D /* Runner */,
153 + );
154 + };
155 +/* End PBXProject section */
156 +
157 +/* Begin PBXResourcesBuildPhase section */
158 + 97C146EC1CF9000F007C117D /* Resources */ = {
159 + isa = PBXResourcesBuildPhase;
160 + buildActionMask = 2147483647;
161 + files = (
162 + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,
163 + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
164 + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
165 + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,
166 + );
167 + runOnlyForDeploymentPostprocessing = 0;
168 + };
169 +/* End PBXResourcesBuildPhase section */
170 +
171 +/* Begin PBXShellScriptBuildPhase section */
172 + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
173 + isa = PBXShellScriptBuildPhase;
174 + buildActionMask = 2147483647;
175 + files = (
176 + );
177 + inputPaths = (
178 + );
179 + name = "Thin Binary";
180 + outputPaths = (
181 + );
182 + runOnlyForDeploymentPostprocessing = 0;
183 + shellPath = /bin/sh;
184 + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
185 + };
186 + 9740EEB61CF901F6004384FC /* Run Script */ = {
187 + isa = PBXShellScriptBuildPhase;
188 + buildActionMask = 2147483647;
189 + files = (
190 + );
191 + inputPaths = (
192 + );
193 + name = "Run Script";
194 + outputPaths = (
195 + );
196 + runOnlyForDeploymentPostprocessing = 0;
197 + shellPath = /bin/sh;
198 + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
199 + };
200 +/* End PBXShellScriptBuildPhase section */
201 +
202 +/* Begin PBXSourcesBuildPhase section */
203 + 97C146EA1CF9000F007C117D /* Sources */ = {
204 + isa = PBXSourcesBuildPhase;
205 + buildActionMask = 2147483647;
206 + files = (
207 + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
208 + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
209 + );
210 + runOnlyForDeploymentPostprocessing = 0;
211 + };
212 +/* End PBXSourcesBuildPhase section */
213 +
214 +/* Begin PBXVariantGroup section */
215 + 97C146FA1CF9000F007C117D /* Main.storyboard */ = {
216 + isa = PBXVariantGroup;
217 + children = (
218 + 97C146FB1CF9000F007C117D /* Base */,
219 + );
220 + name = Main.storyboard;
221 + sourceTree = "<group>";
222 + };
223 + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = {
224 + isa = PBXVariantGroup;
225 + children = (
226 + 97C147001CF9000F007C117D /* Base */,
227 + );
228 + name = LaunchScreen.storyboard;
229 + sourceTree = "<group>";
230 + };
231 +/* End PBXVariantGroup section */
232 +
233 +/* Begin XCBuildConfiguration section */
234 + 249021D3217E4FDB00AE95B9 /* Profile */ = {
235 + isa = XCBuildConfiguration;
236 + buildSettings = {
237 + ALWAYS_SEARCH_USER_PATHS = NO;
238 + CLANG_ANALYZER_NONNULL = YES;
239 + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
240 + CLANG_CXX_LIBRARY = "libc++";
241 + CLANG_ENABLE_MODULES = YES;
242 + CLANG_ENABLE_OBJC_ARC = YES;
243 + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
244 + CLANG_WARN_BOOL_CONVERSION = YES;
245 + CLANG_WARN_COMMA = YES;
246 + CLANG_WARN_CONSTANT_CONVERSION = YES;
247 + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
248 + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
249 + CLANG_WARN_EMPTY_BODY = YES;
250 + CLANG_WARN_ENUM_CONVERSION = YES;
251 + CLANG_WARN_INFINITE_RECURSION = YES;
252 + CLANG_WARN_INT_CONVERSION = YES;
253 + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
254 + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
255 + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
256 + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
257 + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
258 + CLANG_WARN_STRICT_PROTOTYPES = YES;
259 + CLANG_WARN_SUSPICIOUS_MOVE = YES;
260 + CLANG_WARN_UNREACHABLE_CODE = YES;
261 + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
262 + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
263 + COPY_PHASE_STRIP = NO;
264 + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
265 + ENABLE_NS_ASSERTIONS = NO;
266 + ENABLE_STRICT_OBJC_MSGSEND = YES;
267 + GCC_C_LANGUAGE_STANDARD = gnu99;
268 + GCC_NO_COMMON_BLOCKS = YES;
269 + GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
270 + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
271 + GCC_WARN_UNDECLARED_SELECTOR = YES;
272 + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
273 + GCC_WARN_UNUSED_FUNCTION = YES;
274 + GCC_WARN_UNUSED_VARIABLE = YES;
275 + IPHONEOS_DEPLOYMENT_TARGET = 9.0;
276 + MTL_ENABLE_DEBUG_INFO = NO;
277 + SDKROOT = iphoneos;
278 + SUPPORTED_PLATFORMS = iphoneos;
279 + TARGETED_DEVICE_FAMILY = "1,2";
280 + VALIDATE_PRODUCT = YES;
281 + };
282 + name = Profile;
283 + };
284 + 249021D4217E4FDB00AE95B9 /* Profile */ = {
285 + isa = XCBuildConfiguration;
286 + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
287 + buildSettings = {
288 + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
289 + CLANG_ENABLE_MODULES = YES;
290 + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
291 + ENABLE_BITCODE = NO;
292 + FRAMEWORK_SEARCH_PATHS = (
293 + "$(inherited)",
294 + "$(PROJECT_DIR)/Flutter",
295 + );
296 + INFOPLIST_FILE = Runner/Info.plist;
297 + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
298 + LIBRARY_SEARCH_PATHS = (
299 + "$(inherited)",
300 + "$(PROJECT_DIR)/Flutter",
301 + );
302 + PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1;
303 + PRODUCT_NAME = "$(TARGET_NAME)";
304 + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
305 + SWIFT_VERSION = 5.0;
306 + VERSIONING_SYSTEM = "apple-generic";
307 + };
308 + name = Profile;
309 + };
310 + 97C147031CF9000F007C117D /* Debug */ = {
311 + isa = XCBuildConfiguration;
312 + buildSettings = {
313 + ALWAYS_SEARCH_USER_PATHS = NO;
314 + CLANG_ANALYZER_NONNULL = YES;
315 + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
316 + CLANG_CXX_LIBRARY = "libc++";
317 + CLANG_ENABLE_MODULES = YES;
318 + CLANG_ENABLE_OBJC_ARC = YES;
319 + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
320 + CLANG_WARN_BOOL_CONVERSION = YES;
321 + CLANG_WARN_COMMA = YES;
322 + CLANG_WARN_CONSTANT_CONVERSION = YES;
323 + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
324 + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
325 + CLANG_WARN_EMPTY_BODY = YES;
326 + CLANG_WARN_ENUM_CONVERSION = YES;
327 + CLANG_WARN_INFINITE_RECURSION = YES;
328 + CLANG_WARN_INT_CONVERSION = YES;
329 + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
330 + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
331 + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
332 + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
333 + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
334 + CLANG_WARN_STRICT_PROTOTYPES = YES;
335 + CLANG_WARN_SUSPICIOUS_MOVE = YES;
336 + CLANG_WARN_UNREACHABLE_CODE = YES;
337 + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
338 + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
339 + COPY_PHASE_STRIP = NO;
340 + DEBUG_INFORMATION_FORMAT = dwarf;
341 + ENABLE_STRICT_OBJC_MSGSEND = YES;
342 + ENABLE_TESTABILITY = YES;
343 + GCC_C_LANGUAGE_STANDARD = gnu99;
344 + GCC_DYNAMIC_NO_PIC = NO;
345 + GCC_NO_COMMON_BLOCKS = YES;
346 + GCC_OPTIMIZATION_LEVEL = 0;
347 + GCC_PREPROCESSOR_DEFINITIONS = (
348 + "DEBUG=1",
349 + "$(inherited)",
350 + );
351 + GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
352 + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
353 + GCC_WARN_UNDECLARED_SELECTOR = YES;
354 + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
355 + GCC_WARN_UNUSED_FUNCTION = YES;
356 + GCC_WARN_UNUSED_VARIABLE = YES;
357 + IPHONEOS_DEPLOYMENT_TARGET = 9.0;
358 + MTL_ENABLE_DEBUG_INFO = YES;
359 + ONLY_ACTIVE_ARCH = YES;
360 + SDKROOT = iphoneos;
361 + TARGETED_DEVICE_FAMILY = "1,2";
362 + };
363 + name = Debug;
364 + };
365 + 97C147041CF9000F007C117D /* Release */ = {
366 + isa = XCBuildConfiguration;
367 + buildSettings = {
368 + ALWAYS_SEARCH_USER_PATHS = NO;
369 + CLANG_ANALYZER_NONNULL = YES;
370 + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
371 + CLANG_CXX_LIBRARY = "libc++";
372 + CLANG_ENABLE_MODULES = YES;
373 + CLANG_ENABLE_OBJC_ARC = YES;
374 + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
375 + CLANG_WARN_BOOL_CONVERSION = YES;
376 + CLANG_WARN_COMMA = YES;
377 + CLANG_WARN_CONSTANT_CONVERSION = YES;
378 + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
379 + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
380 + CLANG_WARN_EMPTY_BODY = YES;
381 + CLANG_WARN_ENUM_CONVERSION = YES;
382 + CLANG_WARN_INFINITE_RECURSION = YES;
383 + CLANG_WARN_INT_CONVERSION = YES;
384 + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
385 + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
386 + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
387 + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
388 + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
389 + CLANG_WARN_STRICT_PROTOTYPES = YES;
390 + CLANG_WARN_SUSPICIOUS_MOVE = YES;
391 + CLANG_WARN_UNREACHABLE_CODE = YES;
392 + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
393 + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
394 + COPY_PHASE_STRIP = NO;
395 + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
396 + ENABLE_NS_ASSERTIONS = NO;
397 + ENABLE_STRICT_OBJC_MSGSEND = YES;
398 + GCC_C_LANGUAGE_STANDARD = gnu99;
399 + GCC_NO_COMMON_BLOCKS = YES;
400 + GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
401 + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
402 + GCC_WARN_UNDECLARED_SELECTOR = YES;
403 + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
404 + GCC_WARN_UNUSED_FUNCTION = YES;
405 + GCC_WARN_UNUSED_VARIABLE = YES;
406 + IPHONEOS_DEPLOYMENT_TARGET = 9.0;
407 + MTL_ENABLE_DEBUG_INFO = NO;
408 + SDKROOT = iphoneos;
409 + SUPPORTED_PLATFORMS = iphoneos;
410 + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
411 + TARGETED_DEVICE_FAMILY = "1,2";
412 + VALIDATE_PRODUCT = YES;
413 + };
414 + name = Release;
415 + };
416 + 97C147061CF9000F007C117D /* Debug */ = {
417 + isa = XCBuildConfiguration;
418 + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
419 + buildSettings = {
420 + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
421 + CLANG_ENABLE_MODULES = YES;
422 + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
423 + ENABLE_BITCODE = NO;
424 + FRAMEWORK_SEARCH_PATHS = (
425 + "$(inherited)",
426 + "$(PROJECT_DIR)/Flutter",
427 + );
428 + INFOPLIST_FILE = Runner/Info.plist;
429 + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
430 + LIBRARY_SEARCH_PATHS = (
431 + "$(inherited)",
432 + "$(PROJECT_DIR)/Flutter",
433 + );
434 + PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1;
435 + PRODUCT_NAME = "$(TARGET_NAME)";
436 + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
437 + SWIFT_OPTIMIZATION_LEVEL = "-Onone";
438 + SWIFT_VERSION = 5.0;
439 + VERSIONING_SYSTEM = "apple-generic";
440 + };
441 + name = Debug;
442 + };
443 + 97C147071CF9000F007C117D /* Release */ = {
444 + isa = XCBuildConfiguration;
445 + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
446 + buildSettings = {
447 + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
448 + CLANG_ENABLE_MODULES = YES;
449 + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
450 + ENABLE_BITCODE = NO;
451 + FRAMEWORK_SEARCH_PATHS = (
452 + "$(inherited)",
453 + "$(PROJECT_DIR)/Flutter",
454 + );
455 + INFOPLIST_FILE = Runner/Info.plist;
456 + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
457 + LIBRARY_SEARCH_PATHS = (
458 + "$(inherited)",
459 + "$(PROJECT_DIR)/Flutter",
460 + );
461 + PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1;
462 + PRODUCT_NAME = "$(TARGET_NAME)";
463 + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
464 + SWIFT_VERSION = 5.0;
465 + VERSIONING_SYSTEM = "apple-generic";
466 + };
467 + name = Release;
468 + };
469 +/* End XCBuildConfiguration section */
470 +
471 +/* Begin XCConfigurationList section */
472 + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {
473 + isa = XCConfigurationList;
474 + buildConfigurations = (
475 + 97C147031CF9000F007C117D /* Debug */,
476 + 97C147041CF9000F007C117D /* Release */,
477 + 249021D3217E4FDB00AE95B9 /* Profile */,
478 + );
479 + defaultConfigurationIsVisible = 0;
480 + defaultConfigurationName = Release;
481 + };
482 + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = {
483 + isa = XCConfigurationList;
484 + buildConfigurations = (
485 + 97C147061CF9000F007C117D /* Debug */,
486 + 97C147071CF9000F007C117D /* Release */,
487 + 249021D4217E4FDB00AE95B9 /* Profile */,
488 + );
489 + defaultConfigurationIsVisible = 0;
490 + defaultConfigurationName = Release;
491 + };
492 +/* End XCConfigurationList section */
493 + };
494 + rootObject = 97C146E61CF9000F007C117D /* Project object */;
495 +}
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<Workspace
3 + version = "1.0">
4 + <FileRef
5 + location = "group:Runner.xcodeproj">
6 + </FileRef>
7 +</Workspace>
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 +<plist version="1.0">
4 +<dict>
5 + <key>IDEDidComputeMac32BitWarning</key>
6 + <true/>
7 +</dict>
8 +</plist>
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 +<plist version="1.0">
4 +<dict>
5 + <key>PreviewsEnabled</key>
6 + <false/>
7 +</dict>
8 +</plist>
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<Scheme
3 + LastUpgradeVersion = "1020"
4 + version = "1.3">
5 + <BuildAction
6 + parallelizeBuildables = "YES"
7 + buildImplicitDependencies = "YES">
8 + <BuildActionEntries>
9 + <BuildActionEntry
10 + buildForTesting = "YES"
11 + buildForRunning = "YES"
12 + buildForProfiling = "YES"
13 + buildForArchiving = "YES"
14 + buildForAnalyzing = "YES">
15 + <BuildableReference
16 + BuildableIdentifier = "primary"
17 + BlueprintIdentifier = "97C146ED1CF9000F007C117D"
18 + BuildableName = "Runner.app"
19 + BlueprintName = "Runner"
20 + ReferencedContainer = "container:Runner.xcodeproj">
21 + </BuildableReference>
22 + </BuildActionEntry>
23 + </BuildActionEntries>
24 + </BuildAction>
25 + <TestAction
26 + buildConfiguration = "Debug"
27 + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
28 + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
29 + shouldUseLaunchSchemeArgsEnv = "YES">
30 + <Testables>
31 + </Testables>
32 + <MacroExpansion>
33 + <BuildableReference
34 + BuildableIdentifier = "primary"
35 + BlueprintIdentifier = "97C146ED1CF9000F007C117D"
36 + BuildableName = "Runner.app"
37 + BlueprintName = "Runner"
38 + ReferencedContainer = "container:Runner.xcodeproj">
39 + </BuildableReference>
40 + </MacroExpansion>
41 + <AdditionalOptions>
42 + </AdditionalOptions>
43 + </TestAction>
44 + <LaunchAction
45 + buildConfiguration = "Debug"
46 + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
47 + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
48 + launchStyle = "0"
49 + useCustomWorkingDirectory = "NO"
50 + ignoresPersistentStateOnLaunch = "NO"
51 + debugDocumentVersioning = "YES"
52 + debugServiceExtension = "internal"
53 + allowLocationSimulation = "YES">
54 + <BuildableProductRunnable
55 + runnableDebuggingMode = "0">
56 + <BuildableReference
57 + BuildableIdentifier = "primary"
58 + BlueprintIdentifier = "97C146ED1CF9000F007C117D"
59 + BuildableName = "Runner.app"
60 + BlueprintName = "Runner"
61 + ReferencedContainer = "container:Runner.xcodeproj">
62 + </BuildableReference>
63 + </BuildableProductRunnable>
64 + <AdditionalOptions>
65 + </AdditionalOptions>
66 + </LaunchAction>
67 + <ProfileAction
68 + buildConfiguration = "Profile"
69 + shouldUseLaunchSchemeArgsEnv = "YES"
70 + savedToolIdentifier = ""
71 + useCustomWorkingDirectory = "NO"
72 + debugDocumentVersioning = "YES">
73 + <BuildableProductRunnable
74 + runnableDebuggingMode = "0">
75 + <BuildableReference
76 + BuildableIdentifier = "primary"
77 + BlueprintIdentifier = "97C146ED1CF9000F007C117D"
78 + BuildableName = "Runner.app"
79 + BlueprintName = "Runner"
80 + ReferencedContainer = "container:Runner.xcodeproj">
81 + </BuildableReference>
82 + </BuildableProductRunnable>
83 + </ProfileAction>
84 + <AnalyzeAction
85 + buildConfiguration = "Debug">
86 + </AnalyzeAction>
87 + <ArchiveAction
88 + buildConfiguration = "Release"
89 + revealArchiveInOrganizer = "YES">
90 + </ArchiveAction>
91 +</Scheme>
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<Workspace
3 + version = "1.0">
4 + <FileRef
5 + location = "group:Runner.xcodeproj">
6 + </FileRef>
7 +</Workspace>
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 +<plist version="1.0">
4 +<dict>
5 + <key>IDEDidComputeMac32BitWarning</key>
6 + <true/>
7 +</dict>
8 +</plist>
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 +<plist version="1.0">
4 +<dict>
5 + <key>PreviewsEnabled</key>
6 + <false/>
7 +</dict>
8 +</plist>
1 +import UIKit
2 +import Flutter
3 +
4 +@UIApplicationMain
5 +@objc class AppDelegate: FlutterAppDelegate {
6 + override func application(
7 + _ application: UIApplication,
8 + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
9 + ) -> Bool {
10 + GeneratedPluginRegistrant.register(with: self)
11 + return super.application(application, didFinishLaunchingWithOptions: launchOptions)
12 + }
13 +}
1 +{
2 + "images" : [
3 + {
4 + "size" : "20x20",
5 + "idiom" : "iphone",
6 + "filename" : "Icon-App-20x20@2x.png",
7 + "scale" : "2x"
8 + },
9 + {
10 + "size" : "20x20",
11 + "idiom" : "iphone",
12 + "filename" : "Icon-App-20x20@3x.png",
13 + "scale" : "3x"
14 + },
15 + {
16 + "size" : "29x29",
17 + "idiom" : "iphone",
18 + "filename" : "Icon-App-29x29@1x.png",
19 + "scale" : "1x"
20 + },
21 + {
22 + "size" : "29x29",
23 + "idiom" : "iphone",
24 + "filename" : "Icon-App-29x29@2x.png",
25 + "scale" : "2x"
26 + },
27 + {
28 + "size" : "29x29",
29 + "idiom" : "iphone",
30 + "filename" : "Icon-App-29x29@3x.png",
31 + "scale" : "3x"
32 + },
33 + {
34 + "size" : "40x40",
35 + "idiom" : "iphone",
36 + "filename" : "Icon-App-40x40@2x.png",
37 + "scale" : "2x"
38 + },
39 + {
40 + "size" : "40x40",
41 + "idiom" : "iphone",
42 + "filename" : "Icon-App-40x40@3x.png",
43 + "scale" : "3x"
44 + },
45 + {
46 + "size" : "60x60",
47 + "idiom" : "iphone",
48 + "filename" : "Icon-App-60x60@2x.png",
49 + "scale" : "2x"
50 + },
51 + {
52 + "size" : "60x60",
53 + "idiom" : "iphone",
54 + "filename" : "Icon-App-60x60@3x.png",
55 + "scale" : "3x"
56 + },
57 + {
58 + "size" : "20x20",
59 + "idiom" : "ipad",
60 + "filename" : "Icon-App-20x20@1x.png",
61 + "scale" : "1x"
62 + },
63 + {
64 + "size" : "20x20",
65 + "idiom" : "ipad",
66 + "filename" : "Icon-App-20x20@2x.png",
67 + "scale" : "2x"
68 + },
69 + {
70 + "size" : "29x29",
71 + "idiom" : "ipad",
72 + "filename" : "Icon-App-29x29@1x.png",
73 + "scale" : "1x"
74 + },
75 + {
76 + "size" : "29x29",
77 + "idiom" : "ipad",
78 + "filename" : "Icon-App-29x29@2x.png",
79 + "scale" : "2x"
80 + },
81 + {
82 + "size" : "40x40",
83 + "idiom" : "ipad",
84 + "filename" : "Icon-App-40x40@1x.png",
85 + "scale" : "1x"
86 + },
87 + {
88 + "size" : "40x40",
89 + "idiom" : "ipad",
90 + "filename" : "Icon-App-40x40@2x.png",
91 + "scale" : "2x"
92 + },
93 + {
94 + "size" : "76x76",
95 + "idiom" : "ipad",
96 + "filename" : "Icon-App-76x76@1x.png",
97 + "scale" : "1x"
98 + },
99 + {
100 + "size" : "76x76",
101 + "idiom" : "ipad",
102 + "filename" : "Icon-App-76x76@2x.png",
103 + "scale" : "2x"
104 + },
105 + {
106 + "size" : "83.5x83.5",
107 + "idiom" : "ipad",
108 + "filename" : "Icon-App-83.5x83.5@2x.png",
109 + "scale" : "2x"
110 + },
111 + {
112 + "size" : "1024x1024",
113 + "idiom" : "ios-marketing",
114 + "filename" : "Icon-App-1024x1024@1x.png",
115 + "scale" : "1x"
116 + }
117 + ],
118 + "info" : {
119 + "version" : 1,
120 + "author" : "xcode"
121 + }
122 +}
1 +{
2 + "images" : [
3 + {
4 + "idiom" : "universal",
5 + "filename" : "LaunchImage.png",
6 + "scale" : "1x"
7 + },
8 + {
9 + "idiom" : "universal",
10 + "filename" : "LaunchImage@2x.png",
11 + "scale" : "2x"
12 + },
13 + {
14 + "idiom" : "universal",
15 + "filename" : "LaunchImage@3x.png",
16 + "scale" : "3x"
17 + }
18 + ],
19 + "info" : {
20 + "version" : 1,
21 + "author" : "xcode"
22 + }
23 +}
1 +# Launch Screen Assets
2 +
3 +You can customize the launch screen with your own desired assets by replacing the image files in this directory.
4 +
5 +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images.
...\ No newline at end of file ...\ No newline at end of file
1 +<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 +<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
3 + <dependencies>
4 + <deployment identifier="iOS"/>
5 + <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
6 + </dependencies>
7 + <scenes>
8 + <!--View Controller-->
9 + <scene sceneID="EHf-IW-A2E">
10 + <objects>
11 + <viewController id="01J-lp-oVM" sceneMemberID="viewController">
12 + <layoutGuides>
13 + <viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>
14 + <viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>
15 + </layoutGuides>
16 + <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
17 + <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
18 + <subviews>
19 + <imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
20 + </imageView>
21 + </subviews>
22 + <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
23 + <constraints>
24 + <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
25 + <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
26 + </constraints>
27 + </view>
28 + </viewController>
29 + <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
30 + </objects>
31 + <point key="canvasLocation" x="53" y="375"/>
32 + </scene>
33 + </scenes>
34 + <resources>
35 + <image name="LaunchImage" width="168" height="185"/>
36 + </resources>
37 +</document>
1 +<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 +<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
3 + <dependencies>
4 + <deployment identifier="iOS"/>
5 + <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
6 + </dependencies>
7 + <scenes>
8 + <!--Flutter View Controller-->
9 + <scene sceneID="tne-QT-ifu">
10 + <objects>
11 + <viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController">
12 + <layoutGuides>
13 + <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
14 + <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
15 + </layoutGuides>
16 + <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
17 + <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
18 + <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
19 + <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
20 + </view>
21 + </viewController>
22 + <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
23 + </objects>
24 + </scene>
25 + </scenes>
26 +</document>
1 +<?xml version="1.0" encoding="UTF-8"?>
2 +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 +<plist version="1.0">
4 +<dict>
5 + <key>CFBundleDevelopmentRegion</key>
6 + <string>$(DEVELOPMENT_LANGUAGE)</string>
7 + <key>CFBundleExecutable</key>
8 + <string>$(EXECUTABLE_NAME)</string>
9 + <key>CFBundleIdentifier</key>
10 + <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
11 + <key>CFBundleInfoDictionaryVersion</key>
12 + <string>6.0</string>
13 + <key>CFBundleName</key>
14 + <string>flutter_application_1</string>
15 + <key>CFBundlePackageType</key>
16 + <string>APPL</string>
17 + <key>CFBundleShortVersionString</key>
18 + <string>$(FLUTTER_BUILD_NAME)</string>
19 + <key>CFBundleSignature</key>
20 + <string>????</string>
21 + <key>CFBundleVersion</key>
22 + <string>$(FLUTTER_BUILD_NUMBER)</string>
23 + <key>LSRequiresIPhoneOS</key>
24 + <true/>
25 + <key>UILaunchStoryboardName</key>
26 + <string>LaunchScreen</string>
27 + <key>UIMainStoryboardFile</key>
28 + <string>Main</string>
29 + <key>UISupportedInterfaceOrientations</key>
30 + <array>
31 + <string>UIInterfaceOrientationPortrait</string>
32 + <string>UIInterfaceOrientationLandscapeLeft</string>
33 + <string>UIInterfaceOrientationLandscapeRight</string>
34 + </array>
35 + <key>UISupportedInterfaceOrientations~ipad</key>
36 + <array>
37 + <string>UIInterfaceOrientationPortrait</string>
38 + <string>UIInterfaceOrientationPortraitUpsideDown</string>
39 + <string>UIInterfaceOrientationLandscapeLeft</string>
40 + <string>UIInterfaceOrientationLandscapeRight</string>
41 + </array>
42 + <key>UIViewControllerBasedStatusBarAppearance</key>
43 + <false/>
44 +</dict>
45 +</plist>
1 +import 'package:flutter/material.dart';
2 +import './src/screens/Homepage.dart';
3 +
4 +import 'package:flutter_dotenv/flutter_dotenv.dart';
5 +
6 +Future main() async {
7 + await DotEnv().load('.env');
8 + runApp(MyApp());
9 +}
10 +
11 +class MyApp extends StatelessWidget {
12 + // This widget is the root of your application.
13 + @override
14 + Widget build(BuildContext context) {
15 + return MaterialApp(
16 + title: 'SMART MEDICINE BOX',
17 + theme: ThemeData(
18 + primarySwatch: Colors.blue,
19 + ),
20 + home: HomePage(),
21 + );
22 + }
23 +}
1 +import 'package:flutter/material.dart';
2 +import 'dart:convert';
3 +import 'package:http/http.dart' as http;
4 +import 'package:flutter_dotenv/flutter_dotenv.dart';
5 +import 'package:intl/intl.dart';
6 +
7 +import '../utils/user_secure_stoarge.dart';
8 +import 'models/Bottle.dart';
9 +import 'models/Medicine.dart';
10 +import 'package:Smart_Medicine_Box/src/screens/SettingPage.dart';
11 +import 'Register/BottleList.dart';
12 +import 'Register/SearchMedicine.dart';
13 +import 'package:intl/date_symbol_data_local.dart';
14 +
15 +class DashBoard extends StatefulWidget {
16 + int pageNumber;
17 +
18 + DashBoard({
19 + Key key,
20 + this.pageNumber,
21 + }) : super(key: key);
22 +
23 + @override
24 + _DashBoardState createState() => _DashBoardState();
25 +}
26 +
27 +class _DashBoardState extends State<DashBoard> {
28 + int _selectedIndex = 0;
29 + List<Bottle> _bottleList = new List<Bottle>();
30 + //Get BottleList
31 + Future<String> getBottleList() async {
32 + String usertoken = await UserSecureStorage.getUserToken();
33 + String hubid = await UserSecureStorage.getHubId();
34 + http.Response response = await http.get(
35 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle/hub/' + hubid),
36 + headers: {"authorization": usertoken},
37 + );
38 + if (_bottleList.length != 0) {
39 + _bottleList.clear();
40 + }
41 + if (response.statusCode == 200) {
42 + List<dynamic> values = new List<dynamic>();
43 + values = json.decode(response.body);
44 +
45 + for (int i = 0; i < values.length; i++) {
46 + Map<String, dynamic> map = values[i];
47 + _bottleList.add(Bottle.fromJson(map));
48 + return "GET";
49 + }
50 + } else if (response.statusCode == 404) {
51 + return "Not Found";
52 + } else {
53 + return "Error";
54 + }
55 + return "Error";
56 + }
57 +
58 + Widget build(BuildContext context) {
59 + _selectedIndex = widget.pageNumber;
60 + var _tabs = [
61 + ineerInformationpage(context),
62 + mainpage(context),
63 + outerInformationpage(context),
64 + ];
65 +
66 + return WillPopScope(
67 + child: Scaffold(
68 + backgroundColor: Color(0xffe5f4ff),
69 + appBar: AppBar(
70 + iconTheme: IconThemeData(color: Colors.black),
71 + backgroundColor: Colors.white,
72 + title: Text(
73 + 'Smart Medicine Box',
74 + style: TextStyle(
75 + color: Colors.black,
76 + fontSize: 20,
77 + fontFamily: 'Noto',
78 + fontWeight: FontWeight.bold),
79 + ),
80 + actions: [
81 + IconButton(
82 + icon: Icon(
83 + Icons.settings,
84 + color: Colors.black,
85 + ),
86 + onPressed: () {
87 + Navigator.push(
88 + context,
89 + MaterialPageRoute(
90 + builder: (BuildContext context) => SettingPage(),
91 + ));
92 + },
93 + )
94 + ],
95 + ),
96 + drawer: Drawer(
97 + child: ListView(
98 + children: [
99 + DrawerHeader(
100 + child: Text('Drawer Header'),
101 + decoration: BoxDecoration(
102 + color: Colors.blue,
103 + ),
104 + ),
105 + ],
106 + ),
107 + ),
108 + body: _tabs[_selectedIndex],
109 + floatingActionButton: FloatingActionButton(
110 + onPressed: () {
111 + setState(() {});
112 + },
113 + child: const Icon(Icons.refresh_outlined),
114 + backgroundColor: Colors.blue,
115 + ),
116 + bottomNavigationBar: BottomNavigationBar(
117 + type: BottomNavigationBarType.fixed,
118 + backgroundColor: Colors.grey,
119 + selectedItemColor: Colors.blue,
120 + unselectedItemColor: Colors.white.withOpacity(.60),
121 + selectedFontSize: 14,
122 + unselectedFontSize: 14,
123 + currentIndex: _selectedIndex,
124 + onTap: (int index) => {
125 + setState(() {
126 + _onItemTapped(index);
127 + })
128 + },
129 + items: [
130 + BottomNavigationBarItem(
131 + icon: Icon(Icons.device_thermostat), label: 'In'),
132 + BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
133 + BottomNavigationBarItem(
134 + label: 'Out',
135 + icon: Icon(Icons.access_time),
136 + )
137 + ],
138 + ),
139 + ),
140 + onWillPop: () async {
141 + await getBottleList();
142 + Navigator.push(
143 + context,
144 + MaterialPageRoute(
145 + builder: (BuildContext context) => BottleList(),
146 + ));
147 + },
148 + );
149 + }
150 +
151 + void _onItemTapped(int index) {
152 + setState(() {
153 + widget.pageNumber = index;
154 + });
155 + }
156 +}
157 +
158 +Widget mainpage(BuildContext context) {
159 + Medicine _medicineInformation = new Medicine();
160 +
161 + Future<Medicine> _getmedicine() async {
162 + String usertoken = await UserSecureStorage.getUserToken();
163 + String medicineid = await UserSecureStorage.getMedicineId();
164 +
165 + http.Response medicineresponse = await http.get(
166 + Uri.encodeFull(
167 + DotEnv().env['SERVER_URL'] + 'medicine/' + medicineid.toString()),
168 + headers: {"authorization": usertoken},
169 + );
170 +
171 + if (medicineresponse.statusCode == 200) {
172 + Map<String, dynamic> data = jsonDecode(medicineresponse.body);
173 + _medicineInformation = Medicine.fromJson(data);
174 + }
175 + return _medicineInformation;
176 + }
177 +
178 + final Size size = MediaQuery.of(context).size;
179 + return Scaffold(
180 + backgroundColor: Colors.white,
181 + body: SingleChildScrollView(
182 + child: FutureBuilder(
183 + future: _getmedicine(),
184 + builder: (BuildContext context, AsyncSnapshot snapshot) {
185 + if (snapshot.hasData == false) {
186 + return CircularProgressIndicator();
187 + } else if (snapshot.hasError) {
188 + return Padding(
189 + padding: const EdgeInsets.all(8.0),
190 + child: Text(
191 + 'Error: ${snapshot.error}',
192 + style: TextStyle(fontSize: 15),
193 + ),
194 + );
195 + } else {
196 + return Container(
197 + margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
198 + padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
199 + child: Column(
200 + crossAxisAlignment: CrossAxisAlignment.center,
201 + children: <Widget>[
202 + SizedBox(height: 20),
203 + Container(
204 + width: size.width,
205 + padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
206 + margin: EdgeInsets.all(15),
207 + decoration: BoxDecoration(
208 + border: Border.all(),
209 + borderRadius: BorderRadius.all(Radius.circular(
210 + 25.0) // <--- border radius here
211 + ),
212 + ),
213 + child: Column(
214 + children: [
215 + SizedBox(height: 30),
216 + Container(
217 + child: Center(
218 + child: Text(
219 + '${snapshot.data.name}' == null
220 + ? '-'
221 + : '${snapshot.data.name}',
222 + style: TextStyle(
223 + color: Colors.black,
224 + fontSize: 24,
225 + fontFamily: 'NotoSansKR',
226 + fontWeight: FontWeight.w700)),
227 + ),
228 + ),
229 + SizedBox(height: 30),
230 + Container(
231 + width: size.width,
232 + alignment: Alignment(0.9, 0),
233 + child: Wrap(
234 + children: [
235 + Text(
236 + '제조사: ',
237 + style: TextStyle(
238 + color: Colors.grey,
239 + fontSize: 14,
240 + ),
241 + ),
242 + Text(
243 + _medicineInformation.company == null
244 + ? '-'
245 + : _medicineInformation.company,
246 + style: TextStyle(
247 + color: Colors.grey,
248 + fontSize: 14,
249 + ),
250 + ),
251 + ],
252 + ),
253 + ),
254 + SizedBox(height: 30),
255 + Container(
256 + width: size.width,
257 + padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
258 + alignment: Alignment(-1, 0),
259 + child: Wrap(
260 + children: [
261 + Text(
262 + '타겟 층 : ',
263 + style: TextStyle(
264 + color: Colors.grey,
265 + fontSize: 14,
266 + ),
267 + ),
268 + Text(
269 + _medicineInformation.target == null
270 + ? '-'
271 + : _medicineInformation.target,
272 + style: TextStyle(
273 + color: Colors.grey,
274 + fontSize: 14,
275 + ),
276 + ),
277 + ],
278 + ),
279 + ),
280 + SizedBox(height: 15),
281 + Container(
282 + width: size.width,
283 + padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
284 + alignment: Alignment(-1, 0),
285 + child: Wrap(
286 + children: [
287 + Text(
288 + '복약 정보 : ',
289 + style: TextStyle(
290 + color: Colors.grey,
291 + fontSize: 14,
292 + ),
293 + ),
294 + Text(
295 + _medicineInformation.dosage == null
296 + ? '-'
297 + : _medicineInformation.dosage,
298 + style: TextStyle(
299 + color: Colors.grey,
300 + fontSize: 14,
301 + ),
302 + ),
303 + ],
304 + ),
305 + ),
306 + SizedBox(height: 10),
307 + Container(
308 + width: size.width,
309 + padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
310 + alignment: Alignment(-1, 0),
311 + child: Column(
312 + children: [
313 + SizedBox(
314 + height: 12,
315 + ),
316 + Container(
317 + width: size.width,
318 + child: Text(
319 + '경고',
320 + style: TextStyle(
321 + color: Colors.redAccent, fontSize: 14),
322 + ),
323 + ),
324 + SizedBox(height: 12),
325 + Container(
326 + width: size.width,
327 + child: Text(
328 + _medicineInformation.warn == null
329 + ? '-'
330 + : _medicineInformation.warn,
331 + style: TextStyle(
332 + color: Colors.redAccent, fontSize: 14),
333 + ),
334 + ),
335 + ],
336 + ),
337 + ),
338 + ],
339 + ),
340 + ),
341 + GestureDetector(
342 + child: Container(
343 + width: size.width * 0.8,
344 + height: 46,
345 + margin: EdgeInsets.only(bottom: 0),
346 + child: FlatButton(
347 + padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
348 + onPressed: () async {
349 + String bottleid =
350 + await UserSecureStorage.getBottleId();
351 + Navigator.push(
352 + context,
353 + MaterialPageRoute(
354 + builder: (BuildContext context) => SearchMedicine(
355 + bottleId: bottleid,
356 + ),
357 + ),
358 + );
359 + },
360 + child: Text(
361 + '약 검색',
362 + textScaleFactor: 1.0,
363 + style: TextStyle(
364 + color: Colors.white,
365 + fontSize: 16,
366 + fontFamily: 'Noto',
367 + fontWeight: FontWeight.bold),
368 + ),
369 + color: Color(0xff1674f6),
370 + shape: RoundedRectangleBorder(
371 + borderRadius: BorderRadius.circular(50)),
372 + ),
373 + ),
374 + ),
375 + ],
376 + ),
377 + );
378 + }
379 + },
380 + ),
381 + ),
382 + );
383 +}
384 +
385 +Widget ineerInformationpage(BuildContext context) {
386 + //get bottle
387 + Future<Bottle> _getbottle() async {
388 + String usertoken = await UserSecureStorage.getUserToken();
389 + String bottleid = await UserSecureStorage.getBottleId();
390 + Bottle _bottleinformation = new Bottle();
391 + http.Response response = await http.get(
392 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle/' + bottleid),
393 + headers: {"authorization": usertoken});
394 +
395 + if (response.statusCode == 200) {
396 + Map<String, dynamic> jsonData = jsonDecode(response.body);
397 + _bottleinformation = Bottle.fromJson(jsonData);
398 + }
399 + return _bottleinformation;
400 + }
401 +
402 + final Size size = MediaQuery.of(context).size;
403 +
404 + return Scaffold(
405 + backgroundColor: Colors.white,
406 + body: FutureBuilder(
407 + future: _getbottle(),
408 + builder: (BuildContext context, AsyncSnapshot snapshot) {
409 + if (snapshot.hasData == false) {
410 + return CircularProgressIndicator();
411 + } else if (snapshot.hasError) {
412 + return Padding(
413 + padding: const EdgeInsets.all(8.0),
414 + child: Text(
415 + 'Error: ${snapshot.error}',
416 + style: TextStyle(fontSize: 15),
417 + ),
418 + );
419 + } else {
420 + return Container(
421 + height: size.height * 0.9,
422 + margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
423 + padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
424 + child: Column(
425 + crossAxisAlignment: CrossAxisAlignment.center,
426 + children: <Widget>[
427 + Container(
428 + padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
429 + height: size.height * 0.08,
430 + width: size.width,
431 + child: Center(
432 + child: Text(
433 + 'Inside Information',
434 + textAlign: TextAlign.center,
435 + textScaleFactor: 1.0,
436 + style: TextStyle(
437 + color: Colors.black,
438 + fontSize: 32,
439 + fontFamily: 'NotoSansKR',
440 + fontWeight: FontWeight.w700),
441 + ),
442 + ),
443 + ),
444 + Container(
445 + padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
446 + margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
447 + height: size.height * 0.25,
448 + width: size.width,
449 + child: Column(
450 + children: <Widget>[
451 + Flexible(
452 + child: Row(
453 + mainAxisAlignment: MainAxisAlignment.center,
454 + children: <Widget>[
455 + Container(
456 + width: size.width * 0.43,
457 + height: size.width * 0.45,
458 + margin: const EdgeInsets.all(5.0),
459 + padding: const EdgeInsets.fromLTRB(10, 5, 10, 10),
460 + decoration: BoxDecoration(
461 + color: Color(0xff8E97FD),
462 + borderRadius: BorderRadius.circular(10.0),
463 + ),
464 + child: Column(
465 + children: [
466 + Container(
467 + width: size.width,
468 + height: size.height * 0.05,
469 + child: Center(
470 + child: Text(
471 + '약병 내부 온도',
472 + textAlign: TextAlign.center,
473 + textScaleFactor: 1.0,
474 + style: TextStyle(
475 + color: Colors.white,
476 + fontSize: 24,
477 + fontFamily: 'NotoSansKR',
478 + fontWeight: FontWeight.w800),
479 + ),
480 + ),
481 + ),
482 + Container(
483 + width: size.width,
484 + height: size.height * 0.145,
485 + child: Center(
486 + child: Row(
487 + mainAxisAlignment:
488 + MainAxisAlignment.center,
489 + children: [
490 + Text(
491 + '${snapshot.data.temperature}' ==
492 + null
493 + ? '-'
494 + : '${snapshot.data.temperature}',
495 + textAlign: TextAlign.center,
496 + textScaleFactor: 1.0,
497 + style: TextStyle(
498 + color: Colors.white,
499 + fontSize: 50,
500 + fontFamily: 'NotoSansKR',
501 + fontWeight: FontWeight.w800),
502 + ),
503 + Text(
504 + '℃',
505 + textAlign: TextAlign.center,
506 + textScaleFactor: 1.0,
507 + style: TextStyle(
508 + color: Colors.white,
509 + fontSize: 50,
510 + fontFamily: 'NotoSansKR',
511 + fontWeight: FontWeight.w800),
512 + )
513 + ],
514 + ),
515 + ),
516 + ),
517 + ],
518 + ),
519 + ),
520 + Container(
521 + width: size.width * 0.43,
522 + height: size.width * 0.45,
523 + margin: const EdgeInsets.all(5.0),
524 + padding: const EdgeInsets.fromLTRB(10, 5, 10, 10),
525 + decoration: BoxDecoration(
526 + color: Color(0xff8E97FD),
527 + borderRadius: BorderRadius.circular(10.0),
528 + ),
529 + child: Column(
530 + children: [
531 + Container(
532 + width: size.width,
533 + height: size.height * 0.05,
534 + child: Center(
535 + child: Text(
536 + '약병 내부 습도',
537 + textAlign: TextAlign.center,
538 + textScaleFactor: 1.0,
539 + style: TextStyle(
540 + color: Colors.white,
541 + fontSize: 24,
542 + fontFamily: 'NotoSansKR',
543 + fontWeight: FontWeight.w800),
544 + ),
545 + ),
546 + ),
547 + Container(
548 + width: size.width,
549 + height: size.height * 0.14,
550 + child: Center(
551 + child: Row(
552 + mainAxisAlignment:
553 + MainAxisAlignment.center,
554 + children: [
555 + Text(
556 + snapshot.data.humidity.toString() ==
557 + null
558 + ? '-'
559 + : snapshot.data.humidity
560 + .toString(),
561 + textAlign: TextAlign.center,
562 + textScaleFactor: 1.0,
563 + style: TextStyle(
564 + color: Colors.white,
565 + fontSize: 50,
566 + fontFamily: 'NotoSansKR',
567 + fontWeight: FontWeight.w800),
568 + ),
569 + Text(
570 + '%',
571 + textAlign: TextAlign.center,
572 + textScaleFactor: 1.0,
573 + style: TextStyle(
574 + color: Colors.white,
575 + fontSize: 50,
576 + fontFamily: 'NotoSansKR',
577 + fontWeight: FontWeight.w800),
578 + )
579 + ],
580 + ),
581 + ),
582 + ),
583 + ],
584 + ),
585 + ),
586 + ],
587 + ),
588 + ),
589 + ],
590 + ),
591 + ),
592 + Container(
593 + padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
594 + margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
595 + height: size.height * 0.3,
596 + width: size.width,
597 + child: Column(
598 + children: <Widget>[
599 + Flexible(
600 + child: Row(
601 + mainAxisAlignment: MainAxisAlignment.center,
602 + children: <Widget>[
603 + Container(
604 + width: size.width * 0.43,
605 + height: size.width * 0.45,
606 + margin: const EdgeInsets.all(5.0),
607 + padding: const EdgeInsets.fromLTRB(10, 5, 10, 10),
608 + decoration: BoxDecoration(
609 + color: Color(0xff8E97FD),
610 + borderRadius: BorderRadius.circular(10.0),
611 + ),
612 + child: Column(
613 + children: [
614 + Container(
615 + width: size.width,
616 + height: size.height * 0.05,
617 + child: Center(
618 + child: Text(
619 + '약병 내부 잔량',
620 + textAlign: TextAlign.center,
621 + textScaleFactor: 1.0,
622 + style: TextStyle(
623 + color: Colors.white,
624 + fontSize: 24,
625 + fontFamily: 'NotoSansKR',
626 + fontWeight: FontWeight.w800),
627 + ),
628 + ),
629 + ),
630 + Container(
631 + width: size.width,
632 + height: size.height * 0.14,
633 + child: Center(
634 + child: Row(
635 + mainAxisAlignment:
636 + MainAxisAlignment.center,
637 + children: [
638 + Text(
639 + snapshot.data.balance.toString() ==
640 + null
641 + ? '-'
642 + : snapshot.data.balance
643 + .toString(),
644 + textAlign: TextAlign.center,
645 + textScaleFactor: 1.0,
646 + style: TextStyle(
647 + color: Colors.white,
648 + fontSize: 80,
649 + fontFamily: 'NotoSansKR',
650 + fontWeight: FontWeight.w800),
651 + ),
652 + Text(
653 + '%',
654 + textAlign: TextAlign.center,
655 + textScaleFactor: 1.0,
656 + style: TextStyle(
657 + color: Colors.white,
658 + fontSize: 60,
659 + fontFamily: 'NotoSansKR',
660 + fontWeight: FontWeight.w800),
661 + )
662 + ],
663 + ),
664 + ),
665 + ),
666 + ],
667 + ),
668 + ),
669 + Container(
670 + width: size.width * 0.43,
671 + height: size.width * 0.45,
672 + margin: const EdgeInsets.all(5.0),
673 + padding: const EdgeInsets.fromLTRB(10, 5, 10, 10),
674 + decoration: BoxDecoration(
675 + color: Color(0xff8E97FD),
676 + borderRadius: BorderRadius.circular(10.0),
677 + ),
678 + child: Column(
679 + children: [
680 + Container(
681 + width: size.width,
682 + height: size.height * 0.05,
683 + child: Center(
684 + child: Text(
685 + '최근 개폐 시간',
686 + textAlign: TextAlign.center,
687 + textScaleFactor: 1.0,
688 + style: TextStyle(
689 + color: Colors.white,
690 + fontSize: 24,
691 + fontFamily: 'NotoSansKR',
692 + fontWeight: FontWeight.w800),
693 + ),
694 + ),
695 + ),
696 + Container(
697 + width: size.width,
698 + height: size.height * 0.14,
699 + child: Center(
700 + child: Text(
701 + snapshot.data.recentOpen == null
702 + ? '-'
703 + : DateFormat.Hm().format(
704 + snapshot.data.recentOpen),
705 + textAlign: TextAlign.center,
706 + textScaleFactor: 1.0,
707 + style: TextStyle(
708 + color: Colors.white,
709 + fontSize: 60,
710 + fontFamily: 'NotoSansKR',
711 + fontWeight: FontWeight.w800),
712 + ),
713 + ),
714 + ),
715 + ],
716 + ),
717 + ),
718 + ],
719 + ),
720 + ),
721 + ],
722 + ),
723 + ),
724 + ],
725 + ),
726 + );
727 + }
728 + },
729 + ),
730 + );
731 +}
732 +
733 +Widget outerInformationpage(BuildContext context) {
734 + Bottle _bottleinformation = new Bottle();
735 + //get bottle
736 + Future<Bottle> _getbottle() async {
737 + String usertoken = await UserSecureStorage.getUserToken();
738 + String bottleid = await UserSecureStorage.getBottleId();
739 + Bottle _bottleinformation = new Bottle();
740 + http.Response response = await http.get(
741 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle/' + bottleid),
742 + headers: {"authorization": usertoken});
743 +
744 + if (response.statusCode == 200) {
745 + Map<String, dynamic> jsonData = jsonDecode(response.body);
746 +
747 + _bottleinformation = Bottle.fromJson(jsonData);
748 + }
749 + return _bottleinformation;
750 + }
751 +
752 + final Size size = MediaQuery.of(context).size;
753 + return Scaffold(
754 + backgroundColor: Colors.white,
755 + body: FutureBuilder(
756 + future: _getbottle(),
757 + builder: (BuildContext context, AsyncSnapshot snapshot) {
758 + if (snapshot.hasData == false) {
759 + return CircularProgressIndicator();
760 + } else if (snapshot.hasError) {
761 + return Padding(
762 + padding: const EdgeInsets.all(8.0),
763 + child: Text(
764 + 'Error: ${snapshot.error}',
765 + style: TextStyle(fontSize: 15),
766 + ),
767 + );
768 + } else {
769 + return Container(
770 + height: size.height * 0.9,
771 + margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
772 + padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
773 + child: Column(
774 + crossAxisAlignment: CrossAxisAlignment.center,
775 + children: <Widget>[
776 + Container(
777 + padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
778 + height: size.height * 0.08,
779 + width: size.width,
780 + child: Center(
781 + child: Text(
782 + 'Outside Information',
783 + textAlign: TextAlign.center,
784 + textScaleFactor: 1.0,
785 + style: TextStyle(
786 + color: Colors.black,
787 + fontSize: 32,
788 + fontFamily: 'NotoSansKR',
789 + fontWeight: FontWeight.w700),
790 + ),
791 + ),
792 + ),
793 + Container(
794 + padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
795 + margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
796 + height: size.height * 0.20,
797 + width: size.width,
798 + child: Column(
799 + children: <Widget>[
800 + Flexible(
801 + child: Column(
802 + mainAxisAlignment: MainAxisAlignment.center,
803 + children: <Widget>[
804 + Container(
805 + padding: EdgeInsets.fromLTRB(5, 5, 5, 0),
806 + width: size.width * 0.9,
807 + height: size.height * 0.18,
808 + decoration: BoxDecoration(
809 + color: Color(0xff8E97FD),
810 + borderRadius: BorderRadius.circular(10.0),
811 + ),
812 + child: Column(
813 + children: [
814 + Container(
815 + width: size.width,
816 + height: size.height * 0.05,
817 + child: Center(
818 + child: Text(
819 + '권장 약 복용량',
820 + textAlign: TextAlign.center,
821 + textScaleFactor: 1.0,
822 + style: TextStyle(
823 + color: Colors.white,
824 + fontSize: 28,
825 + fontFamily: 'NotoSansKR',
826 + fontWeight: FontWeight.w800),
827 + ),
828 + ),
829 + ),
830 + Container(
831 + width: size.width,
832 + height: size.height * 0.12,
833 + child: Row(
834 + mainAxisAlignment:
835 + MainAxisAlignment.center,
836 + children: [
837 + Text(
838 + snapshot.data.dosage == null
839 + ? '-'
840 + : snapshot.data.dosage
841 + .toString(),
842 + textAlign: TextAlign.center,
843 + textScaleFactor: 1.0,
844 + style: TextStyle(
845 + color: Colors.white,
846 + fontSize: 80,
847 + fontFamily: 'NotoSansKR',
848 + fontWeight: FontWeight.w800),
849 + ),
850 + Text(
851 + ' 개',
852 + textScaleFactor: 1.0,
853 + style: TextStyle(
854 + color: Colors.white,
855 + fontSize: 64,
856 + fontFamily: 'NotoSansKR',
857 + fontWeight: FontWeight.w800),
858 + )
859 + ],
860 + ),
861 + ),
862 + ],
863 + ),
864 + ),
865 + ],
866 + ),
867 + ),
868 + ],
869 + ),
870 + ),
871 + ],
872 + ),
873 + );
874 + }
875 + }),
876 + );
877 +}
1 +import 'package:flutter/material.dart';
2 +import 'package:flutter/services.dart';
3 +import '../shared/colors.dart';
4 +import 'package:flutter_screenutil/flutter_screenutil.dart';
5 +import './Register/SignInPage.dart';
6 +import 'Register/SignUpLocal.dart';
7 +
8 +class HomePage extends StatefulWidget {
9 + HomePage({Key key}) : super(key: key);
10 +
11 + @override
12 + _HomePageState createState() => _HomePageState();
13 +}
14 +
15 +/// first page class
16 +class _HomePageState extends State<HomePage> {
17 + @override
18 + void initState() {
19 + super.initState();
20 + }
21 +
22 + @override
23 + Widget build(BuildContext context) {
24 + final Size size = MediaQuery.of(context).size;
25 +
26 + return Scaffold(
27 + body: GestureDetector(
28 + child: Container(
29 + color: Colors.white,
30 + height: size.height,
31 + child: Center(
32 + child: MediaQuery(
33 + data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
34 + child: Column(
35 + mainAxisAlignment: MainAxisAlignment.center,
36 + crossAxisAlignment: CrossAxisAlignment.center,
37 + children: <Widget>[
38 + Container(
39 + height: size.height * 0.5,
40 + child: Column(
41 + mainAxisAlignment: MainAxisAlignment.end,
42 + children: <Widget>[
43 + Row(
44 + mainAxisAlignment: MainAxisAlignment.center,
45 + children: <Widget>[
46 + Text(
47 + 'SMART MEDICINE BOX',
48 + textScaleFactor: 1.0,
49 + style: TextStyle(
50 + color: Color(0xff004ca2),
51 + fontSize: 30,
52 + fontFamily: 'Noto',
53 + fontWeight: FontWeight.bold),
54 + ),
55 + ],
56 + ),
57 + AnimatedOpacity(
58 + opacity: 1,
59 + duration: Duration(milliseconds: 500),
60 + child: Container(
61 + padding: EdgeInsets.fromLTRB(0, 0, 0, 20),
62 + child: Image.asset('images/main_logo.png',
63 + width: 200, height: 250)),
64 + ),
65 + ],
66 + ),
67 + ),
68 + Container(
69 + height: size.height * 0.3,
70 + child: Column(
71 + mainAxisAlignment: MainAxisAlignment.end,
72 + crossAxisAlignment: CrossAxisAlignment.center,
73 + mainAxisSize: MainAxisSize.max,
74 + children: <Widget>[
75 + GestureDetector(
76 + child: Container(
77 + width: size.width * 0.8,
78 + height: 46,
79 + margin: EdgeInsets.only(bottom: 0),
80 + child: FlatButton(
81 + padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
82 + onPressed: () {
83 + Navigator.push(
84 + context,
85 + MaterialPageRoute(
86 + builder: (BuildContext context) =>
87 + SignInPage(),
88 + ),
89 + );
90 + },
91 + child: Text(
92 + '로그인',
93 + textScaleFactor: 1.0,
94 + style: TextStyle(
95 + color: Colors.white,
96 + fontSize: 16,
97 + fontFamily: 'Noto',
98 + fontWeight: FontWeight.bold),
99 + ),
100 + color: Color(0xff1674f6),
101 + shape: RoundedRectangleBorder(
102 + borderRadius: BorderRadius.circular(50)),
103 + ),
104 + ),
105 + ),
106 + GestureDetector(
107 + child: Container(
108 + width: size.width * 0.8,
109 + padding: EdgeInsets.all(0),
110 + child: OutlineButton(
111 + padding: EdgeInsets.fromLTRB(0, 25, 0, 15),
112 + onPressed: () {
113 + Navigator.push(
114 + context,
115 + MaterialPageRoute(
116 + builder: (BuildContext context) =>
117 + SignUpLocal(),
118 + ),
119 + );
120 + },
121 + child: Text(
122 + '회원 가입',
123 + textScaleFactor: 1.0,
124 + style:
125 + TextStyle(fontSize: 16, fontFamily: 'Noto'),
126 + ),
127 + textColor: Colors.black,
128 + highlightedBorderColor: highlightColor,
129 + borderSide: BorderSide.none,
130 + shape: RoundedRectangleBorder(
131 + borderRadius: BorderRadius.circular(50)),
132 + ),
133 + ),
134 + ),
135 + ],
136 + ),
137 + ),
138 + ],
139 + ),
140 + )),
141 + ),
142 + ),
143 + backgroundColor: bgColor,
144 + );
145 + }
146 +}
1 +import 'dart:convert';
2 +import 'package:flutter/material.dart';
3 +import 'package:flutter/services.dart';
4 +import 'package:http/http.dart' as http;
5 +import 'package:flutter_dotenv/flutter_dotenv.dart';
6 +import '../models/Bottle.dart';
7 +import '../DashBoard.dart';
8 +import '../../utils/user_secure_stoarge.dart';
9 +
10 +class BottleList extends StatefulWidget {
11 + BottleList({Key key}) : super(key: key);
12 +
13 + @override
14 + _BottleListState createState() => _BottleListState();
15 +}
16 +
17 +class _BottleListState extends State<BottleList> {
18 + String valueText;
19 + List<Bottle> _bottleList = new List<Bottle>();
20 + TextEditingController _textFieldController = TextEditingController();
21 + Future<String> getBottleList() async {
22 + String hubid = await UserSecureStorage.getHubId();
23 + String usertoken = await UserSecureStorage.getUserToken();
24 +
25 + http.Response response = await http.get(
26 + Uri.encodeFull(
27 + DotEnv().env['SERVER_URL'] + 'bottle/hub/' + hubid.toString()),
28 + headers: {"authorization": usertoken},
29 + );
30 +
31 + if (_bottleList.length != 0) {
32 + _bottleList.clear();
33 + }
34 + if (response.statusCode == 200) {
35 + List<dynamic> values = new List<dynamic>();
36 + values = json.decode(response.body);
37 +
38 + for (int i = 0; i < values.length; i++) {
39 + Map<String, dynamic> map = values[i];
40 + _bottleList.add(Bottle.fromJson(map));
41 + }
42 +
43 + return "GET";
44 + } else if (response.statusCode == 404) {
45 + return "Not Found";
46 + } else {
47 + return "Error";
48 + }
49 + }
50 +
51 + Widget build(BuildContext context) {
52 + final Size size = MediaQuery.of(context).size;
53 + return WillPopScope(
54 + child: Scaffold(
55 + appBar: AppBar(
56 + backgroundColor: Colors.white,
57 + leading: new Icon(Icons.medical_services_rounded,
58 + color: Colors.black, size: 45.0),
59 + title: Text(
60 + 'Smart Medicine Box',
61 + style: TextStyle(
62 + color: Colors.black,
63 + fontSize: 23,
64 + fontFamily: 'Noto',
65 + fontWeight: FontWeight.bold),
66 + ),
67 + ),
68 + body: FutureBuilder(
69 + future: getBottleList(),
70 + builder: (BuildContext context, AsyncSnapshot snapshot) {
71 + if (snapshot.hasData == false) {
72 + return CircularProgressIndicator();
73 + } else if (snapshot.hasError) {
74 + return Padding(
75 + padding: const EdgeInsets.all(8.0),
76 + child: Text(
77 + 'Error: ${snapshot.error}',
78 + style: TextStyle(fontSize: 15),
79 + ),
80 + );
81 + } else {
82 + return Container(
83 + height: size.height,
84 + child: Column(
85 + mainAxisAlignment: MainAxisAlignment.center,
86 + children: <Widget>[
87 + SizedBox(height: 10),
88 + Container(
89 + height: size.height * 0.07,
90 + width: size.width,
91 + child: Center(
92 + child: Text(
93 + '등록된 약병 리스트',
94 + textScaleFactor: 1.0,
95 + style: TextStyle(
96 + fontSize: 28,
97 + fontFamily: 'Noto',
98 + fontWeight: FontWeight.bold),
99 + ),
100 + ),
101 + ),
102 + SizedBox(height: 10),
103 + Expanded(
104 + child: GridView.builder(
105 + padding: const EdgeInsets.all(30),
106 + itemCount:
107 + _bottleList.length == null ? 0 : _bottleList.length,
108 + gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
109 + maxCrossAxisExtent: 200,
110 + crossAxisSpacing: 10,
111 + mainAxisSpacing: 10,
112 + ),
113 + itemBuilder: (BuildContext context, int index) {
114 + return InkResponse(
115 + splashColor: Colors.transparent,
116 + child: Container(
117 + height: 140,
118 + padding: const EdgeInsets.all(10),
119 + decoration: BoxDecoration(
120 + border: Border.all(),
121 + borderRadius: BorderRadius.all(
122 + Radius.circular(16.0),
123 + ),
124 + ),
125 + child: Column(
126 + children: [
127 + Container(
128 + decoration: BoxDecoration(
129 + border: Border(
130 + bottom: BorderSide(
131 + color: Colors.black,
132 + width: 1,
133 + style: BorderStyle.solid),
134 + ),
135 + ),
136 + height: 40,
137 + child: Row(
138 + mainAxisAlignment:
139 + MainAxisAlignment.spaceBetween,
140 + children: [
141 + Container(
142 + height: 40,
143 + child: Center(
144 + child: Text(
145 + '${_bottleList[index].bottleId}',
146 + style: TextStyle(
147 + color: Colors.black,
148 + fontSize: 20,
149 + fontFamily: 'Noto',
150 + fontWeight: FontWeight.bold),
151 + ),
152 + ),
153 + ),
154 + Container(
155 + child: IconButton(
156 + alignment: Alignment(0.9, 0),
157 + icon: Icon(
158 + Icons.create_sharp,
159 + color: Colors.black,
160 + ),
161 + onPressed: () {},
162 + ),
163 + ),
164 + ],
165 + ),
166 + ),
167 + SizedBox(height: 10),
168 + Container(
169 + height: 90,
170 + child: Icon(
171 + Icons.medical_services_outlined,
172 + size: 100,
173 + ),
174 + )
175 + ],
176 + ),
177 + ),
178 + onTap: () {
179 + UserSecureStorage.setBottleId(
180 + _bottleList[index].bottleId.toString());
181 + UserSecureStorage.setMedicineId(
182 + _bottleList[index].medicineId.toString());
183 + Navigator.push(
184 + context,
185 + MaterialPageRoute(
186 + builder: (BuildContext context) => DashBoard(
187 + pageNumber: 0,
188 + ),
189 + ),
190 + );
191 + },
192 + );
193 + },
194 + ),
195 + )
196 + ],
197 + ),
198 + );
199 + }
200 + },
201 + ),
202 + ),
203 + onWillPop: () {
204 + SystemNavigator.pop();
205 + },
206 + );
207 + }
208 +}
1 +import 'package:Smart_Medicine_Box/src/screens/DashBoard.dart';
2 +import 'package:Smart_Medicine_Box/src/screens/Homepage.dart';
3 +import 'package:flutter/material.dart';
4 +import 'package:flutter/cupertino.dart';
5 +import 'dart:convert';
6 +import 'package:http/http.dart' as http;
7 +import 'package:flutter_dotenv/flutter_dotenv.dart';
8 +import '../models/Medicine.dart';
9 +import '../../utils/user_secure_stoarge.dart';
10 +
11 +class DetailMedicine extends StatefulWidget {
12 + Medicine searchMedicine;
13 + String bottleId;
14 + DetailMedicine({Key key, this.searchMedicine, this.bottleId})
15 + : super(key: key);
16 + @override
17 + _DetailMedicineState createState() => _DetailMedicineState();
18 +}
19 +
20 +class _DetailMedicineState extends State<DetailMedicine> {
21 + final medicineDosageController = TextEditingController();
22 + //약 등록
23 + Future<String> patchMedcine() async {
24 + String usertoken = await UserSecureStorage.getUserToken();
25 +
26 + http.Response response = await http.patch(
27 + Uri.encodeFull(
28 + DotEnv().env['SERVER_URL'] + 'bottle/' + widget.bottleId),
29 + headers: {
30 + "Content-Type": "application/json",
31 + "authorization": usertoken
32 + },
33 + body: jsonEncode({
34 + 'medicineId': widget.searchMedicine.medicineId,
35 + 'dosage': medicineDosageController.text
36 + }));
37 +
38 + if (response.statusCode == 200) {
39 + String usertoken = await UserSecureStorage.setMedicineId(
40 + widget.searchMedicine.medicineId.toString());
41 + return "Complete";
42 + } else if (response.statusCode == 404) {
43 + return "약병이 존재하지 않습니다.";
44 + } else if (response.statusCode == 403) {
45 + return "약병에 접근할 권한이 없습니다.";
46 + } else {
47 + return "알 수 없는 오류";
48 + }
49 + }
50 +
51 + Widget build(BuildContext context) {
52 + final Size size = MediaQuery.of(context).size;
53 + return MaterialApp(
54 + home: Scaffold(
55 + appBar: AppBar(
56 + backgroundColor: Colors.white,
57 + leading: new Icon(Icons.medical_services_rounded,
58 + color: Colors.black, size: 45.0),
59 + title: Text(
60 + 'Smart Medicine Box',
61 + style: TextStyle(
62 + color: Colors.black,
63 + fontSize: 23,
64 + fontFamily: 'Noto',
65 + fontWeight: FontWeight.bold),
66 + ),
67 + ),
68 + body: SingleChildScrollView(
69 + scrollDirection: Axis.vertical,
70 + child: Column(
71 + crossAxisAlignment: CrossAxisAlignment.center,
72 + children: <Widget>[
73 + SizedBox(height: 30),
74 + Container(
75 + padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
76 + height: size.height * 0.08,
77 + width: size.width,
78 + child: Center(
79 + child: Text(
80 + '세부 약 정보',
81 + textAlign: TextAlign.center,
82 + textScaleFactor: 1.0,
83 + style: TextStyle(
84 + color: Colors.black,
85 + fontSize: 36,
86 + fontFamily: 'NotoSansKR',
87 + fontWeight: FontWeight.w700),
88 + ),
89 + ),
90 + ),
91 + SizedBox(height: 5),
92 + Container(
93 + width: size.width,
94 + padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
95 + margin: EdgeInsets.all(15),
96 + decoration: BoxDecoration(
97 + border: Border.all(),
98 + borderRadius: BorderRadius.all(
99 + Radius.circular(25.0) // <--- border radius here
100 + ),
101 + ),
102 + child: Column(
103 + children: [
104 + SizedBox(height: 40),
105 + Container(
106 + child: Center(
107 + child: Text(widget.searchMedicine.name,
108 + style: TextStyle(
109 + color: Colors.black,
110 + fontSize: 24,
111 + fontFamily: 'NotoSansKR',
112 + fontWeight: FontWeight.w700)),
113 + ),
114 + ),
115 + SizedBox(height: 15),
116 + Container(
117 + width: size.width,
118 + alignment: Alignment(0.9, 0),
119 + child: Text(
120 + '제조사: ' + widget.searchMedicine.company,
121 + style: TextStyle(
122 + color: Colors.grey,
123 + fontSize: 20,
124 + ),
125 + ),
126 + ),
127 + SizedBox(height: 30),
128 + Container(
129 + width: size.width,
130 + padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
131 + alignment: Alignment(-1, 0),
132 + child: Text(
133 + '타겟 층 : ' + widget.searchMedicine.target,
134 + style: TextStyle(color: Colors.black, fontSize: 16),
135 + ),
136 + ),
137 + SizedBox(height: 15),
138 + Container(
139 + width: size.width,
140 + padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
141 + alignment: Alignment(-1, 0),
142 + child: Text(
143 + '복약 정보 : ' + widget.searchMedicine.dosage,
144 + style: TextStyle(color: Colors.black, fontSize: 16),
145 + ),
146 + ),
147 + SizedBox(height: 10),
148 + Container(
149 + width: size.width,
150 + padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
151 + alignment: Alignment(-1, 0),
152 + child: Column(
153 + children: [
154 + SizedBox(
155 + height: 12,
156 + ),
157 + Container(
158 + width: size.width,
159 + child: Text(
160 + '경고',
161 + style: TextStyle(
162 + color: Colors.redAccent, fontSize: 14),
163 + ),
164 + ),
165 + SizedBox(height: 12),
166 + Container(
167 + width: size.width,
168 + child: Text(
169 + widget.searchMedicine.warn,
170 + style: TextStyle(
171 + color: Colors.redAccent, fontSize: 14),
172 + ),
173 + ),
174 + ],
175 + ),
176 + ),
177 + ],
178 + ),
179 + ),
180 + SizedBox(height: 12),
181 + Container(
182 + height: size.height * 0.1,
183 + padding: const EdgeInsets.fromLTRB(20, 10, 20, 5),
184 + child: TextFormField(
185 + keyboardType: TextInputType.text,
186 + controller: medicineDosageController,
187 + decoration: InputDecoration(
188 + border: OutlineInputBorder(),
189 + errorBorder: InputBorder.none,
190 + disabledBorder: InputBorder.none,
191 + hintText: '하루에 섭취할 적정 복용량을 숫자만 입력하세요',
192 + ),
193 + style: TextStyle(
194 + fontSize: 16,
195 + fontFamily: 'NotoSansKR',
196 + fontWeight: FontWeight.w600)),
197 + ),
198 + SizedBox(height: 12),
199 + Container(
200 + height: size.height * 0.07,
201 + width: size.width * 0.8,
202 + child: FlatButton(
203 + padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
204 + onPressed: () async {
205 + String saveMessage = await patchMedcine();
206 + if (saveMessage == "Complete") {
207 + showDialog(
208 + context: context,
209 + builder: (BuildContext context) {
210 + return AlertDialog(
211 + title: new Text('약 등록'),
212 + content: new Text('약 등록이 완료 되었습니다.'),
213 + actions: <Widget>[
214 + new FlatButton(
215 + child: new Text('Close'),
216 + onPressed: () {
217 + Navigator.push(
218 + context,
219 + MaterialPageRoute(
220 + builder: (BuildContext context) =>
221 + DashBoard(
222 + pageNumber: 1,
223 + ),
224 + ),
225 + );
226 + })
227 + ],
228 + );
229 + });
230 + }
231 + },
232 + child: Text(
233 + '약 등록',
234 + textScaleFactor: 1.0,
235 + style: TextStyle(
236 + color: Colors.white,
237 + fontSize: 20,
238 + fontFamily: 'Noto',
239 + fontWeight: FontWeight.bold),
240 + ),
241 + color: Color(0xff1674f6),
242 + shape: RoundedRectangleBorder(
243 + borderRadius: BorderRadius.circular(50)),
244 + ),
245 + ),
246 + SizedBox(height: 30)
247 + ],
248 + ),
249 + ),
250 + ),
251 + );
252 + }
253 +}
1 +import 'package:flutter/cupertino.dart';
2 +import 'package:flutter/material.dart';
3 +import 'dart:convert';
4 +import 'package:http/http.dart' as http;
5 +import 'package:flutter_dotenv/flutter_dotenv.dart';
6 +// Screen import
7 +import 'RegisterBottle.dart';
8 +import '../models/Bottle.dart';
9 +import 'BottleList.dart';
10 +import '../../utils/user_secure_stoarge.dart';
11 +
12 +class HubList extends StatefulWidget {
13 + List<int> hublist;
14 + HubList({Key key, this.hublist}) : super(key: key);
15 +
16 + @override
17 + _HubListState createState() => _HubListState();
18 +}
19 +
20 +class _HubListState extends State<HubList> {
21 + List<Bottle> _bottleList = new List<Bottle>();
22 + //Get BottleList
23 + Future<String> getBottleList(int hubid) async {
24 + String usertoken = await UserSecureStorage.getUserToken();
25 + http.Response response = await http.get(
26 + Uri.encodeFull(
27 + DotEnv().env['SERVER_URL'] + 'bottle/hub/' + hubid.toString()),
28 + headers: {"authorization": usertoken},
29 + );
30 +
31 + if (_bottleList.length != 0) {
32 + _bottleList.clear();
33 + }
34 + if (response.statusCode == 200) {
35 + List<dynamic> values = new List<dynamic>();
36 + values = json.decode(response.body);
37 +
38 + for (int i = 0; i < values.length; i++) {
39 + Map<String, dynamic> map = values[i];
40 + _bottleList.add(Bottle.fromJson(map));
41 + return "GET";
42 + }
43 + } else if (response.statusCode == 404) {
44 + return "Not Found";
45 + } else {
46 + return "Error";
47 + }
48 + return "Error";
49 + }
50 +
51 + Widget build(BuildContext context) {
52 + final Size size = MediaQuery.of(context).size;
53 + return Scaffold(
54 + appBar: AppBar(
55 + backgroundColor: Colors.white,
56 + leading: new Icon(Icons.medical_services_rounded,
57 + color: Colors.black, size: 45.0),
58 + title: Text(
59 + 'Smart Medicine Box',
60 + style: TextStyle(
61 + color: Colors.black,
62 + fontSize: 23,
63 + fontFamily: 'Noto',
64 + fontWeight: FontWeight.bold),
65 + ),
66 + ),
67 + body: Container(
68 + height: size.height,
69 + child: Column(
70 + mainAxisAlignment: MainAxisAlignment.center,
71 + children: <Widget>[
72 + Container(
73 + height: size.height * 0.1,
74 + width: size.width,
75 + child: Center(
76 + child: Text(
77 + '등록된 허브 리스트',
78 + textScaleFactor: 1.0,
79 + style: TextStyle(
80 + fontSize: 28,
81 + fontFamily: 'Noto',
82 + fontWeight: FontWeight.bold),
83 + ),
84 + ),
85 + decoration: BoxDecoration(border: Border.all()),
86 + ),
87 + SizedBox(height: 30),
88 + Expanded(
89 + child: ListView.separated(
90 + padding: const EdgeInsets.all(30),
91 + itemCount: widget.hublist.length,
92 + itemBuilder: (BuildContext context, int index) {
93 + return Container(
94 + padding: EdgeInsets.all(8.0),
95 + decoration: BoxDecoration(
96 + border: Border.all(),
97 + borderRadius: BorderRadius.all(Radius.circular(25.0)),
98 + ),
99 + child: ListTile(
100 + title: Text(
101 + 'HUB ID: ' + '${widget.hublist[index]}',
102 + style: TextStyle(
103 + color: Colors.black,
104 + fontSize: 20,
105 + fontFamily: 'Noto',
106 + fontWeight: FontWeight.bold),
107 + ),
108 + trailing: Icon(Icons.arrow_forward),
109 + onTap: () async {
110 + //허브 id로 가져와서 있으면 바로 넘기기
111 + var result =
112 + await getBottleList(widget.hublist[index]);
113 + if (result == "GET") {
114 + UserSecureStorage.setHubId(
115 + widget.hublist[index].toString());
116 + Navigator.push(
117 + context,
118 + MaterialPageRoute(
119 + builder: (BuildContext context) =>
120 + BottleList(),
121 + ));
122 + } else if (result == "Not Found") {
123 + showDialog(
124 + context: context,
125 + builder: (BuildContext context) {
126 + return AlertDialog(
127 + title: new Text('Error'),
128 + content: new Text('등록된 약병이 없습니다.'),
129 + actions: <Widget>[
130 + new FlatButton(
131 + child: new Text('등록'),
132 + onPressed: () {
133 + UserSecureStorage.setHubId(
134 + widget.hublist[index].toString());
135 + Navigator.push(
136 + context,
137 + MaterialPageRoute(
138 + builder:
139 + (BuildContext context) =>
140 + RegisterBottle(),
141 + ));
142 + })
143 + ],
144 + );
145 + },
146 + );
147 + }
148 + },
149 + ),
150 + );
151 + },
152 + separatorBuilder: (BuildContext contetx, int index) =>
153 + const Divider(),
154 + ),
155 + )
156 + ],
157 + )),
158 + );
159 + }
160 +}
1 +import 'package:Smart_Medicine_Box/src/screens/DashBoard.dart';
2 +import 'package:Smart_Medicine_Box/src/screens/Register/BottleList.dart';
3 +import 'package:flutter/cupertino.dart';
4 +import 'dart:convert';
5 +import 'package:flutter/material.dart';
6 +import 'package:http/http.dart' as http;
7 +import 'package:flutter_dotenv/flutter_dotenv.dart';
8 +
9 +import 'SearchMedicine.dart';
10 +import '../../utils/user_secure_stoarge.dart';
11 +
12 +class RegisterBottle extends StatefulWidget {
13 + final String hubid;
14 + final bool modify_bottle;
15 + RegisterBottle({Key key, this.hubid, this.modify_bottle}) : super(key: key);
16 + @override
17 + _RegisterBottleState createState() => _RegisterBottleState();
18 +}
19 +
20 +class _RegisterBottleState extends State<RegisterBottle> {
21 + final medicineBottleIDController = TextEditingController();
22 +
23 + Future<String> registerhub_Validate() async {
24 + String usertoken = await UserSecureStorage.getUserToken();
25 + String hubid = await UserSecureStorage.getHubId();
26 +
27 + http.Response bottleresponse = await http.post(
28 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle'),
29 + headers: {
30 + "Content-Type": "application/json",
31 + "authorization": usertoken
32 + },
33 + body: jsonEncode(
34 + {'bottleId': medicineBottleIDController.text, 'hubId': hubid}));
35 +
36 + if (bottleresponse.statusCode == 201) {
37 + return "등록 완료";
38 + } else if (bottleresponse.statusCode == 404) {
39 + return "Hub 없음";
40 + } else if (bottleresponse.statusCode == 403) {
41 + return "유저 정보 없음 ";
42 + } else if (bottleresponse.statusCode == 404) {
43 + return "HOST 없음";
44 + } else {
45 + return "오류";
46 + }
47 + }
48 +
49 + Widget build(BuildContext context) {
50 + final Size size = MediaQuery.of(context).size;
51 + // int goals = 60;
52 + // int points = 75;
53 +
54 + return Scaffold(
55 + backgroundColor: Colors.white,
56 + body: ListView(
57 + children: <Widget>[
58 + Padding(
59 + padding: const EdgeInsets.fromLTRB(20, 25, 20, 0),
60 + child: Row(
61 + children: <Widget>[
62 + Text(
63 + '약병 등록',
64 + textScaleFactor: 1.0,
65 + style: TextStyle(fontSize: 34),
66 + )
67 + ],
68 + ),
69 + ),
70 + Padding(
71 + padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
72 + child: Row(
73 + children: <Widget>[
74 + Text(
75 + 'SmartMedicine 회원가입',
76 + textScaleFactor: 1.0,
77 + style: TextStyle(fontSize: 16),
78 + )
79 + ],
80 + ),
81 + ),
82 + MediaQuery(
83 + data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
84 + child: Container(
85 + height: size.height * 0.6,
86 + child: Padding(
87 + padding: const EdgeInsets.fromLTRB(20, 5, 20, 20),
88 + child: new Column(
89 + mainAxisAlignment: MainAxisAlignment.center,
90 + children: <Widget>[
91 + TextFormField(
92 + keyboardType: TextInputType.text,
93 + controller: medicineBottleIDController,
94 + decoration: InputDecoration(
95 + labelText: '약병 ID',
96 + helperText: '현재 사용하시는 약병의 고유번호를 입력하세요',
97 + ),
98 + ),
99 + ],
100 + ),
101 + ),
102 + ),
103 + ),
104 + Container(
105 + height: 80,
106 + padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
107 + child: RaisedButton(
108 + onPressed: () async {
109 + String saveMessage = await registerhub_Validate();
110 + print(saveMessage);
111 + print(widget.modify_bottle);
112 + if (saveMessage == "등록 완료" && widget.modify_bottle == false) {
113 + showDialog(
114 + context: context,
115 + builder: (BuildContext context) {
116 + return AlertDialog(
117 + title: new Text('약병 등록'),
118 + content: new Text('약병 등록이 완료 되었습니다.'),
119 + actions: <Widget>[
120 + new FlatButton(
121 + child: new Text('Close'),
122 + onPressed: () {
123 + UserSecureStorage.setBottleId(
124 + medicineBottleIDController.text);
125 + Navigator.push(
126 + context,
127 + MaterialPageRoute(
128 + builder: (BuildContext context) =>
129 + SearchMedicine(
130 + bottleId: medicineBottleIDController.text,
131 + ),
132 + ),
133 + );
134 + },
135 + ),
136 + ],
137 + );
138 + },
139 + );
140 + } else if (saveMessage == "등록 완료" &&
141 + widget.modify_bottle == true) {
142 + print('asdg');
143 + await showDialog(
144 + context: context,
145 + builder: (BuildContext context) {
146 + return AlertDialog(
147 + title: new Text('약병 등록'),
148 + content: new Text('약병 등록이 완료 되었습니다.'),
149 + actions: <Widget>[
150 + new FlatButton(
151 + child: new Text('Close'),
152 + onPressed: () {
153 + Navigator.of(context).pop();
154 + },
155 + ),
156 + ],
157 + );
158 + },
159 + );
160 + Navigator.of(context).pop();
161 + } else {
162 + showDialog(
163 + context: context,
164 + builder: (BuildContext context) {
165 + return AlertDialog(
166 + title: new Text('오류'),
167 + content: new Text(saveMessage),
168 + actions: <Widget>[
169 + new FlatButton(
170 + child: new Text('Close'),
171 + onPressed: () {
172 + Navigator.of(context).pop();
173 + },
174 + )
175 + ],
176 + );
177 + },
178 + );
179 + }
180 + },
181 + shape: RoundedRectangleBorder(
182 + borderRadius: new BorderRadius.circular(18.0),
183 + side: BorderSide(color: Colors.blue)),
184 + color: Color(0xff1674f6),
185 + child: Text(
186 + '약병 등록',
187 + textScaleFactor: 1.0,
188 + style: TextStyle(
189 + fontSize: 16,
190 + color: Colors.white,
191 + fontWeight: FontWeight.bold),
192 + ),
193 + ),
194 + )
195 + ],
196 + ),
197 + );
198 + }
199 +}
1 +import 'package:Smart_Medicine_Box/src/screens/SettingPage/HubModifyList.dart';
2 +import 'package:flutter/cupertino.dart';
3 +import 'dart:convert';
4 +import 'package:flutter/material.dart';
5 +import 'package:http/http.dart' as http;
6 +import 'package:flutter_dotenv/flutter_dotenv.dart';
7 +
8 +import 'RegisterBottle.dart';
9 +import '../../utils/user_secure_stoarge.dart';
10 +
11 +class RegisterHub extends StatefulWidget {
12 + final int modify_hub;
13 +
14 + RegisterHub({Key key, this.modify_hub}) : super(key: key);
15 + @override
16 + _RegisterHubState createState() => _RegisterHubState();
17 +}
18 +
19 +class _RegisterHubState extends State<RegisterHub> {
20 + final medicineBottleIDController = TextEditingController();
21 + final medicineHubIDController = TextEditingController();
22 + final medicineHubPortController = TextEditingController();
23 + final medicineHubHostController = TextEditingController();
24 +
25 + Future<String> registerhub_Validate() async {
26 + String usertoken = await UserSecureStorage.getUserToken();
27 + http.Response hubresponse = await http.post(
28 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'),
29 + headers: {
30 + "Content-Type": "application/json",
31 + "authorization": usertoken
32 + },
33 + body: jsonEncode({
34 + 'hubId': medicineHubIDController.text,
35 + 'host': medicineHubHostController.text,
36 + 'port': medicineHubPortController.text,
37 + }));
38 + print(hubresponse.statusCode);
39 + if (hubresponse.statusCode == 201) {
40 + return "허브 등록 완료";
41 + } else if (hubresponse.statusCode == 409) {
42 + return "이미 존재하는 hub";
43 + } else {
44 + return "오류";
45 + }
46 + }
47 +
48 + Widget build(BuildContext context) {
49 + final Size size = MediaQuery.of(context).size;
50 + // int goals = 60;
51 + // int points = 75;
52 +
53 + return Scaffold(
54 + backgroundColor: Colors.white,
55 + body: ListView(
56 + children: <Widget>[
57 + Padding(
58 + padding: const EdgeInsets.fromLTRB(20, 25, 20, 0),
59 + child: Row(
60 + children: <Widget>[
61 + Text(
62 + '허브 등록',
63 + textScaleFactor: 1.0,
64 + style: TextStyle(fontSize: 34),
65 + )
66 + ],
67 + ),
68 + ),
69 + Padding(
70 + padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
71 + child: Row(
72 + children: <Widget>[
73 + Text(
74 + 'SmartMedicine 허브 등록',
75 + textScaleFactor: 1.0,
76 + style: TextStyle(fontSize: 16),
77 + )
78 + ],
79 + ),
80 + ),
81 + MediaQuery(
82 + data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
83 + child: Container(
84 + height: size.height * 0.6,
85 + child: Padding(
86 + padding: const EdgeInsets.fromLTRB(20, 5, 20, 20),
87 + child: new Column(
88 + mainAxisAlignment: MainAxisAlignment.center,
89 + children: <Widget>[
90 + TextFormField(
91 + keyboardType: TextInputType.text,
92 + controller: medicineHubIDController,
93 + decoration: InputDecoration(
94 + labelText: '허브 ID',
95 + helperText: '현자 등록하시는 허브의 고유 번호를 입력하세요',
96 + ),
97 + ),
98 + TextFormField(
99 + keyboardType: TextInputType.text,
100 + controller: medicineHubHostController,
101 + decoration: InputDecoration(
102 + labelText: 'Host',
103 + helperText: '현재 사용하시는 허브의 HOST를 입력하세요',
104 + ),
105 + ),
106 + TextFormField(
107 + keyboardType: TextInputType.text,
108 + controller: medicineHubPortController,
109 + decoration: InputDecoration(
110 + labelText: 'Port',
111 + helperText: '현재 사용하시는 허브의 PORT를 입력하세요',
112 + ),
113 + ),
114 + ],
115 + ),
116 + ),
117 + ),
118 + ),
119 + Container(
120 + height: 80,
121 + padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
122 + child: RaisedButton(
123 + onPressed: () async {
124 + String saveMessage = await registerhub_Validate();
125 + print(saveMessage);
126 + print(widget.modify_hub);
127 + if (saveMessage == "허브 등록 완료" && widget.modify_hub == 0) {
128 + UserSecureStorage.setHubId(medicineHubIDController.text);
129 + Navigator.push(
130 + context,
131 + MaterialPageRoute(
132 + builder: (BuildContext context) => RegisterBottle(
133 + hubid: medicineHubIDController.text,
134 + modify_bottle: false,
135 + ),
136 + ),
137 + );
138 + } else if (saveMessage == "허브 등록 완료" &&
139 + widget.modify_hub == 1) {
140 + Navigator.of(context).pop();
141 + } else {
142 + showDialog(
143 + context: context,
144 + builder: (BuildContext context) {
145 + return AlertDialog(
146 + title: new Text('오류'),
147 + content: new Text(saveMessage),
148 + actions: <Widget>[
149 + new FlatButton(
150 + child: new Text('close'),
151 + onPressed: () {
152 + Navigator.of(context).pop();
153 + },
154 + )
155 + ],
156 + );
157 + },
158 + );
159 + }
160 + },
161 + shape: RoundedRectangleBorder(
162 + borderRadius: new BorderRadius.circular(18.0),
163 + side: BorderSide(color: Colors.blue)),
164 + color: Color(0xff1674f6),
165 + child: Text(
166 + '허브 등록 ',
167 + textScaleFactor: 1.0,
168 + style: TextStyle(
169 + fontSize: 16,
170 + color: Colors.white,
171 + fontWeight: FontWeight.bold),
172 + ),
173 + ),
174 + )
175 + ],
176 + ),
177 + );
178 + }
179 +}
1 +import 'dart:convert';
2 +import 'package:flutter/material.dart';
3 +import 'package:flutter/services.dart';
4 +import 'package:http/http.dart' as http;
5 +import 'package:flutter_dotenv/flutter_dotenv.dart';
6 +import '../models/Medicine.dart';
7 +import 'DetailMedicine.dart';
8 +import '../../utils/user_secure_stoarge.dart';
9 +
10 +class SearchMedicine extends StatefulWidget {
11 + String bottleId;
12 + SearchMedicine({Key key, this.bottleId}) : super(key: key);
13 + @override
14 + _SearchMedicineState createState() => _SearchMedicineState();
15 +}
16 +
17 +class _SearchMedicineState extends State<SearchMedicine> {
18 + List<Medicine> _medicineList = new List<Medicine>();
19 + final medicineNameController = TextEditingController();
20 + final medicineCompanyController = TextEditingController();
21 +
22 + Future<String> postMeicineList() async {
23 + String usertoken = await UserSecureStorage.getUserToken();
24 + http.Response response = await http.post(
25 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'medicine'),
26 + headers: {
27 + "Content-Type": "application/json",
28 + "authorization": usertoken
29 + },
30 + body: jsonEncode({
31 + 'name': medicineNameController.text,
32 + 'company': medicineCompanyController.text,
33 + }));
34 +
35 + if (_medicineList.length != 0) {
36 + _medicineList.clear();
37 + }
38 + if (response.statusCode == 200) {
39 + List<dynamic> values = new List<dynamic>();
40 + values = json.decode(response.body);
41 + for (int i = 0; i < values.length; i++) {
42 + Map<String, dynamic> map = values[i];
43 + _medicineList.add(Medicine.fromJson(map));
44 + }
45 + return "GET";
46 + } else {
47 + return "Not Found";
48 + }
49 + }
50 +
51 + Widget build(BuildContext context) {
52 + bool isForward = false;
53 + final Size size = MediaQuery.of(context).size;
54 + // int goals = 60;
55 + // int points = 75;
56 +
57 + return Scaffold(
58 + appBar: AppBar(
59 + backgroundColor: Colors.white,
60 + leading: new Icon(Icons.medical_services_rounded,
61 + color: Colors.black, size: 45.0),
62 + title: Text(
63 + 'Smart Medicine Box',
64 + style: TextStyle(
65 + color: Colors.black,
66 + fontSize: 23,
67 + fontFamily: 'Noto',
68 + fontWeight: FontWeight.bold),
69 + ),
70 + ),
71 + body: Container(
72 + height: size.height,
73 + padding: const EdgeInsets.all(10),
74 + decoration: BoxDecoration(
75 + border: Border.all(),
76 + ),
77 + child: Column(
78 + crossAxisAlignment: CrossAxisAlignment.center,
79 + children: <Widget>[
80 + SizedBox(height: 20),
81 + Container(
82 + height: size.height * 0.13,
83 + decoration: BoxDecoration(
84 + border: Border.all(),
85 + color: Colors.white,
86 + borderRadius: BorderRadius.circular(25),
87 + ),
88 + child: Row(
89 + children: [
90 + Column(
91 + children: [
92 + Container(
93 + height: size.height * 0.0635,
94 + width: size.width * 0.75,
95 + child: Row(
96 + children: [
97 + Container(
98 + width: size.width * 0.16,
99 + padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
100 + child: Text('약이름:',
101 + textAlign: TextAlign.center,
102 + style: TextStyle(
103 + fontSize: 16,
104 + fontFamily: 'NotoSansKR',
105 + fontWeight: FontWeight.w600)),
106 + ),
107 + Container(
108 + padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
109 + width: size.width * 0.55,
110 + child: TextFormField(
111 + keyboardType: TextInputType.text,
112 + controller: medicineNameController,
113 + decoration: InputDecoration(
114 + border: InputBorder.none,
115 + focusedBorder: InputBorder.none,
116 + enabledBorder: InputBorder.none,
117 + errorBorder: InputBorder.none,
118 + disabledBorder: InputBorder.none,
119 + hintText: '약 이름을 입력하세요',
120 + ),
121 + style: TextStyle(
122 + fontSize: 16,
123 + fontFamily: 'NotoSansKR',
124 + fontWeight: FontWeight.w600)),
125 + )
126 + ],
127 + ),
128 + decoration: BoxDecoration(
129 + border: Border(
130 + bottom: BorderSide(
131 + color: Colors.black,
132 + width: 1,
133 + style: BorderStyle.solid),
134 + right: BorderSide(
135 + color: Colors.black,
136 + width: 1,
137 + style: BorderStyle.solid),
138 + ),
139 + ),
140 + ),
141 + Container(
142 + height: size.height * 0.0635,
143 + width: size.width * 0.75,
144 + child: Row(
145 + children: [
146 + Container(
147 + width: size.width * 0.16,
148 + padding: const EdgeInsets.fromLTRB(5, 0, 0, 3),
149 + child: Text('제조사:',
150 + textAlign: TextAlign.center,
151 + style: TextStyle(
152 + fontSize: 16,
153 + fontFamily: 'NotoSansKR',
154 + fontWeight: FontWeight.w600)),
155 + ),
156 + Container(
157 + padding: const EdgeInsets.fromLTRB(6, 0, 0, 0),
158 + width: size.width * 0.50,
159 + child: TextFormField(
160 + keyboardType: TextInputType.text,
161 + controller: medicineCompanyController,
162 + decoration: InputDecoration(
163 + border: InputBorder.none,
164 + focusedBorder: InputBorder.none,
165 + enabledBorder: InputBorder.none,
166 + errorBorder: InputBorder.none,
167 + disabledBorder: InputBorder.none,
168 + hintText: '약 제조사 이름을 입력하세요',
169 + ),
170 + style: TextStyle(
171 + fontSize: 16,
172 + fontFamily: 'NotoSansKR',
173 + fontWeight: FontWeight.w600)),
174 + )
175 + ],
176 + ),
177 + decoration: BoxDecoration(
178 + border: Border(
179 + right: BorderSide(
180 + color: Colors.black,
181 + width: 1,
182 + style: BorderStyle.solid),
183 + ),
184 + ),
185 + ),
186 + ],
187 + ),
188 + Container(
189 + height: size.height * 0.0635 * 2,
190 + width: size.width * 0.14,
191 + padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
192 + child: IconButton(
193 + icon: Icon(Icons.search, size: 40),
194 + onPressed: () async {
195 + String saveMessage = await postMeicineList();
196 + if (saveMessage == "GET") {
197 + setState(() {});
198 + }
199 + //검색 함수를 여기다가
200 + },
201 + ),
202 + ),
203 + ],
204 + ),
205 + ),
206 + SizedBox(height: 20),
207 + Expanded(
208 + child: ListView.separated(
209 + itemBuilder: (BuildContext context, int index) {
210 + return Container(
211 + padding: EdgeInsets.all(8.0),
212 + decoration: BoxDecoration(border: Border.all()),
213 + child: ListTile(
214 + title: Text(
215 + 'Medicine: ' + _medicineList[index].name,
216 + style: TextStyle(
217 + color: Colors.black,
218 + fontSize: 20,
219 + fontFamily: 'Noto',
220 + fontWeight: FontWeight.bold),
221 + ),
222 + trailing: Icon(Icons.arrow_forward),
223 + onTap: () async {
224 + Navigator.push(
225 + context,
226 + MaterialPageRoute(
227 + builder: (BuildContext context) =>
228 + DetailMedicine(
229 + searchMedicine: _medicineList[index],
230 + bottleId: widget.bottleId,
231 + ),
232 + ));
233 + }),
234 + );
235 + },
236 + separatorBuilder: (BuildContext contetx, int index) =>
237 + const Divider(),
238 + itemCount: _medicineList.length == null
239 + ? 0
240 + : _medicineList.length))
241 + ],
242 + ),
243 + ),
244 + );
245 + }
246 +}
1 +import 'dart:convert';
2 +import 'package:flutter/material.dart';
3 +import 'package:flutter/services.dart';
4 +import 'package:http/http.dart' as http;
5 +import 'package:flutter_dotenv/flutter_dotenv.dart';
6 +
7 +import '../../utils/user_secure_stoarge.dart';
8 +import 'HubList.dart';
9 +import 'RegsiterHub.dart';
10 +import '../models/User.dart';
11 +
12 +class SignInPage extends StatefulWidget {
13 + @override
14 + _SignInPageState createState() => _SignInPageState();
15 +}
16 +
17 +///
18 +class _SignInPageState extends State<SignInPage> {
19 + bool passwordVisible = false;
20 + bool _validateEmail = false;
21 + bool _validatePassword = false;
22 +
23 + final emailController = TextEditingController();
24 + final passwordController = TextEditingController();
25 +
26 + User user;
27 + List<int> _hublist = new List<int>(); //허브이름을 만들어야 할 것 같은데 임시로 허브 id만 고르게 함
28 +
29 + //Login 함수
30 + Future<String> login(String _email, String _password) async {
31 + http.Response response = await http.post(
32 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'auth/login'),
33 + headers: {"Content-Type": "application/json"},
34 + body: jsonEncode(
35 + {
36 + 'userId': _email,
37 + 'password': _password,
38 + },
39 + ),
40 + );
41 + if (response.statusCode == 200) {
42 + Map<String, dynamic> data = jsonDecode(response.body);
43 + user = User.fromJson(data);
44 + UserSecureStorage.setUserToken(user.token);
45 + UserSecureStorage.setUserId(user.userId);
46 + return "로그인 성공";
47 + } else if (response.statusCode == 400) {
48 + return "올바르지 않은 아이디 및 패스워드";
49 + } else {
50 + return "존재하지 않는 아이디 이거나 비밀번호가 불일치 합니다.";
51 + }
52 + }
53 +
54 + //Get Hub List 함수
55 + Future<String> getHubList() async {
56 + String usertoken = await UserSecureStorage.getUserToken();
57 + http.Response response = await http.get(
58 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'),
59 + headers: {"authorization": usertoken},
60 + );
61 + List<dynamic> values = new List<dynamic>();
62 + if (_hublist.length != 0) {
63 + _hublist.clear();
64 + }
65 + if (response.statusCode == 200) {
66 + values = json.decode(response.body);
67 + for (int i = 0; i < values.length; i++) {
68 + _hublist.add(values[i]['hubId']);
69 + }
70 + return "get완료";
71 + } else if (response.statusCode == 404) {
72 + return "Not Found";
73 + } else {
74 + return "Error";
75 + }
76 + }
77 +
78 + Widget build(BuildContext context) {
79 + final Size size = MediaQuery.of(context).size;
80 + final mqData = MediaQuery.of(context);
81 + final mqDataScale = mqData.copyWith(textScaleFactor: 1.0);
82 +
83 + return WillPopScope(
84 + onWillPop: () {
85 + if (Navigator.canPop(context)) {
86 + //Navigator.pop(context);
87 + Navigator.of(context).pop();
88 + } else {
89 + SystemNavigator.pop();
90 + }
91 + },
92 + child: Scaffold(
93 + body: Builder(
94 + builder: (BuildContext context) {
95 + return ListView(
96 + children: <Widget>[
97 + Padding(
98 + padding: EdgeInsets.only(top: 25, left: 18, right: 18),
99 + child: Stack(
100 + children: <Widget>[
101 + Column(
102 + mainAxisAlignment: MainAxisAlignment.start,
103 + crossAxisAlignment: CrossAxisAlignment.start,
104 + children: <Widget>[
105 + Padding(
106 + padding: const EdgeInsets.fromLTRB(20, 0, 0, 0),
107 + child: Text('로그인',
108 + textScaleFactor: 1.0,
109 + style: TextStyle(
110 + fontSize: 34,
111 + fontFamily: 'Noto',
112 + fontWeight: FontWeight.bold)),
113 + ),
114 + SizedBox(
115 + height: 40,
116 + ),
117 + Padding(
118 + padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
119 + child: new Column(
120 + children: <Widget>[
121 + MediaQuery(
122 + data: mqDataScale,
123 + child: TextFormField(
124 + keyboardType: TextInputType.text,
125 + controller: emailController,
126 + decoration: InputDecoration(
127 + labelText: '이메일',
128 + helperText: '이메일 주소를 입력해주세요.',
129 + contentPadding:
130 + EdgeInsets.fromLTRB(0, 5, 0, 5),
131 + errorText: _validateEmail
132 + ? '등록되지 않은 아이디입니다.'
133 + : null,
134 + labelStyle: TextStyle(
135 + fontSize: 14,
136 + color: Color(0xff000000)),
137 + helperStyle: TextStyle(
138 + fontSize: 12,
139 + color: Color(0xffb2b2b2)),
140 + // Here is key idea
141 + ),
142 + ),
143 + )
144 + ],
145 + ),
146 + ),
147 + Padding(
148 + padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
149 + child: new Column(
150 + children: <Widget>[
151 + MediaQuery(
152 + data: mqDataScale,
153 + child: TextFormField(
154 + keyboardType: TextInputType.text,
155 + controller: passwordController,
156 + obscureText:
157 + !passwordVisible, //This will obscure text dynamically
158 + decoration: InputDecoration(
159 + labelText: '비밀번호',
160 + helperText: '비밀번호를 입력해 주세요.',
161 + errorText: _validatePassword
162 + ? '비밀번호가 일치하지 않습니다.'
163 + : null,
164 + labelStyle: TextStyle(
165 + fontSize: 14,
166 + color: Color(0xff000000)),
167 + helperStyle: TextStyle(
168 + fontSize: 12,
169 + color: Color(0xffb2b2b2)),
170 + // Here is key idea
171 + suffixIcon: IconButton(
172 + icon: Icon(
173 + // Based on passwordVisible state choose the icon
174 + passwordVisible
175 + ? Icons.visibility
176 + : Icons.visibility_off,
177 + color: Color(0xff2c2c2c),
178 + ),
179 + onPressed: () {
180 + // Update the state i.e. toogle the state of passwordVisible variable
181 + setState(() {
182 + passwordVisible = !passwordVisible;
183 + });
184 + },
185 + ),
186 + ),
187 + ),
188 + )
189 + ],
190 + ),
191 + ),
192 + Row(
193 + mainAxisAlignment: MainAxisAlignment.center,
194 + children: <Widget>[
195 + Container(
196 + width: size.width * 0.8,
197 + height: 46,
198 + child: RaisedButton(
199 + color: Color(0xff1674f6),
200 + child: Text("로그인",
201 + textScaleFactor: 1.0,
202 + style: TextStyle(
203 + color: Colors.white,
204 + fontSize: 16,
205 + fontFamily: 'Noto',
206 + fontWeight: FontWeight.bold)),
207 + onPressed: () async {
208 + String saveMessage = await login(
209 + emailController.text,
210 + passwordController.text);
211 + if (emailController.text.isEmpty ||
212 + passwordController.text.isEmpty) {
213 + showDialog(
214 + context: context,
215 + builder: (BuildContext context) {
216 + return AlertDialog(
217 + title: new Text('이메일 & 비밀번호'),
218 + content: new Text(
219 + '이메일과 비밀번호를 입력해주세요.'),
220 + actions: <Widget>[
221 + new FlatButton(
222 + child: new Text('Close'),
223 + onPressed: () {
224 + Navigator.of(context)
225 + .pop();
226 + })
227 + ],
228 + );
229 + });
230 + } else {
231 + if (saveMessage == "로그인 성공") {
232 + var result = await getHubList();
233 + if (result == "Not Found") {
234 + Navigator.push(
235 + context,
236 + MaterialPageRoute(
237 + builder: (BuildContext
238 + context) =>
239 + RegisterHub(modify_hub: 0),
240 + ));
241 + } else if (result == "get완료") {
242 + Navigator.push(
243 + context,
244 + MaterialPageRoute(
245 + builder: (BuildContext context) =>
246 + HubList(hublist: _hublist),
247 + ),
248 + );
249 + } else {}
250 + } else {
251 + print('Error');
252 + }
253 + }
254 + },
255 + shape: RoundedRectangleBorder(
256 + borderRadius: BorderRadius.circular(20)),
257 + ),
258 + ),
259 + ],
260 + ),
261 + ],
262 + ),
263 + ],
264 + ),
265 + ),
266 + ],
267 + );
268 + },
269 + ),
270 + ),
271 + );
272 + }
273 +}
1 +import 'dart:convert';
2 +import 'package:Smart_Medicine_Box/src/screens/Homepage.dart';
3 +import 'package:flutter/material.dart';
4 +import 'package:http/http.dart' as http;
5 +import 'package:flutter_dotenv/flutter_dotenv.dart';
6 +
7 +import 'RegsiterHub.dart';
8 +
9 +class SignUpLocal extends StatefulWidget {
10 + @override
11 + _SignUpLocalState createState() => _SignUpLocalState();
12 +}
13 +
14 +class _SignUpLocalState extends State<SignUpLocal> {
15 + final emailController = TextEditingController();
16 + final passwordController = TextEditingController();
17 + final passwordValidController = TextEditingController();
18 + bool _validate = false;
19 + int userRole = 0;
20 +
21 + // Initially password is obscure
22 + bool passwordVisible = false;
23 + bool passwordValidationVisible = false;
24 +
25 + Future<String> signup_Validate() async {
26 + http.Response response = await http.post(
27 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'auth/register'),
28 + headers: {"Content-Type": "application/json"},
29 + body: jsonEncode(
30 + {
31 + 'userId': emailController.text,
32 + 'password': passwordController.text,
33 + 'passwordCheck': passwordValidController.text
34 + },
35 + ),
36 + );
37 + if (response.statusCode == 201) {
38 + return "정보 입력 완료";
39 + } else {
40 + return "오류";
41 + }
42 + }
43 +
44 + @override
45 + Widget build(BuildContext context) {
46 + final Size size = MediaQuery.of(context).size;
47 + // int goals = 60;
48 + // int points = 75;
49 +
50 + return Scaffold(
51 + backgroundColor: Colors.white,
52 + body: ListView(
53 + children: <Widget>[
54 + Padding(
55 + padding: const EdgeInsets.fromLTRB(20, 25, 20, 0),
56 + child: Row(
57 + children: <Widget>[
58 + Text(
59 + '회원 가입',
60 + textScaleFactor: 1.0,
61 + style: TextStyle(fontSize: 34),
62 + )
63 + ],
64 + ),
65 + ),
66 + Padding(
67 + padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
68 + child: Row(
69 + children: <Widget>[
70 + Text(
71 + 'SmartMedicine 회원가입',
72 + textScaleFactor: 1.0,
73 + style: TextStyle(fontSize: 16),
74 + )
75 + ],
76 + ),
77 + ),
78 + MediaQuery(
79 + data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
80 + child: Container(
81 + height: size.height * 0.6,
82 + child: Padding(
83 + padding: const EdgeInsets.fromLTRB(20, 5, 20, 20),
84 + child: new Column(
85 + mainAxisAlignment: MainAxisAlignment.center,
86 + children: <Widget>[
87 + TextFormField(
88 + controller: emailController,
89 + keyboardType: TextInputType.text,
90 + decoration: InputDecoration(
91 + labelText: '이메일',
92 + helperText: '아아디로 사용할 이메일 주소를 입력해주세요.',
93 + ),
94 + ),
95 + TextFormField(
96 + keyboardType: TextInputType.text,
97 + controller: passwordController,
98 + obscureText:
99 + !passwordVisible, //This will obscure text dynamically
100 + decoration: InputDecoration(
101 + labelText: '비밀번호',
102 + helperText: '비밀번호를 입력해주세요',
103 + // Here is key idea
104 + suffixIcon: IconButton(
105 + icon: Icon(
106 + // Based on passwordVisible state choose the icon
107 + passwordVisible
108 + ? Icons.visibility
109 + : Icons.visibility_off,
110 + color: Theme.of(context).primaryColorDark,
111 + ),
112 + onPressed: () {
113 + // Update the state i.e. toogle the state of passwordVisible variable
114 + setState(() {
115 + passwordVisible = !passwordVisible;
116 + });
117 + },
118 + ),
119 + ),
120 + ),
121 + TextFormField(
122 + onChanged: (text) {
123 + if (passwordController.text == text) {
124 + setState(() {
125 + _validate = false;
126 + });
127 + } else {
128 + setState(() {
129 + _validate = true;
130 + });
131 + }
132 + },
133 + keyboardType: TextInputType.text,
134 + controller: passwordValidController,
135 + obscureText:
136 + !passwordValidationVisible, //This will obscure text dynamically
137 + decoration: InputDecoration(
138 + labelText: '비밀번호 확인',
139 + helperText: '비밀번호를 확인해주세요',
140 + errorText:
141 + _validate ? '두 비밀번호가 다릅니다. 다시 확인해주세요.' : null,
142 + // Here is key idea
143 + suffixIcon: IconButton(
144 + icon: Icon(
145 + // Based on passwordVisible state choose the icon
146 + passwordValidationVisible
147 + ? Icons.visibility
148 + : Icons.visibility_off,
149 + color: Theme.of(context).primaryColorDark,
150 + ),
151 + onPressed: () {
152 + // Update the state i.e. toogle the state of passwordVisible variable
153 + setState(() {
154 + passwordValidationVisible =
155 + !passwordValidationVisible;
156 + });
157 + },
158 + ),
159 + ),
160 + ),
161 + ],
162 + ),
163 + ),
164 + ),
165 + ),
166 + Container(
167 + height: 80,
168 + padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
169 + child: RaisedButton(
170 + onPressed: () async {
171 + String saveMessage = await signup_Validate();
172 + if (saveMessage == "정보 입력 완료") {
173 + showDialog(
174 + context: context,
175 + builder: (BuildContext context) {
176 + return AlertDialog(
177 + title: new Text('회원 가입'),
178 + content: new Text('회원 가입이 완료 되었습니다.'),
179 + actions: <Widget>[
180 + new FlatButton(
181 + child: new Text('Close'),
182 + onPressed: () {
183 + Navigator.push(
184 + context,
185 + MaterialPageRoute(
186 + builder: (BuildContext context) =>
187 + HomePage()));
188 + })
189 + ],
190 + );
191 + });
192 + } else {
193 + showDialog(
194 + context: context,
195 + builder: (BuildContext context) {
196 + return AlertDialog(
197 + title: new Text('회원 가입 오류'),
198 + content: new Text('정확한 이메일, 비밀번호를 입력해 주세요.'),
199 + actions: <Widget>[
200 + new FlatButton(
201 + child: new Text('Close'),
202 + onPressed: () {
203 + Navigator.of(context).pop();
204 + })
205 + ],
206 + );
207 + });
208 + }
209 + },
210 + shape: RoundedRectangleBorder(
211 + borderRadius: new BorderRadius.circular(18.0),
212 + side: BorderSide(color: Colors.blue)),
213 + color: Color(0xff1674f6),
214 + child: Text(
215 + '회원 가입',
216 + textScaleFactor: 1.0,
217 + style: TextStyle(
218 + fontSize: 16,
219 + color: Colors.white,
220 + fontWeight: FontWeight.bold),
221 + ),
222 + ),
223 + )
224 + ],
225 + ),
226 + bottomNavigationBar: BottomAppBar(
227 + elevation: 0,
228 + child: Container(
229 + height: 70,
230 + child: Column(
231 + mainAxisAlignment: MainAxisAlignment.start,
232 + children: <Widget>[
233 + Padding(
234 + padding: const EdgeInsets.fromLTRB(70, 0, 70, 0),
235 + child: Text(
236 + '회원 가입시, 이용 약관 및 개인정보 처리 방침에 동의하는 것으로 간주합니다..',
237 + style: TextStyle(fontSize: 12, color: Color(0xff747474)),
238 + textAlign: TextAlign.center,
239 + ),
240 + )
241 + ],
242 + ),
243 + ),
244 + ),
245 + );
246 + }
247 +}
1 +import 'package:Smart_Medicine_Box/src/screens/SettingPage/HubModifyList.dart';
2 +import 'package:flutter/material.dart';
3 +import 'package:Smart_Medicine_Box/src/screens/DashBoard.dart';
4 +import 'package:Smart_Medicine_Box/src/screens/SettingPage/Alarm.dart';
5 +import 'package:Smart_Medicine_Box/src/screens/SettingPage/DEVInformation.dart';
6 +import 'package:Smart_Medicine_Box/src/screens/SettingPage/BottleModifyList.dart';
7 +
8 +class SettingPage extends StatefulWidget {
9 + @override
10 + _SettingPageState createState() => _SettingPageState();
11 +}
12 +
13 +class _SettingPageState extends State<SettingPage> {
14 + Widget build(BuildContext context) {
15 + final Size size = MediaQuery.of(context).size;
16 + return MaterialApp(
17 + title: 'Welcome to Flutter',
18 + home: Scaffold(
19 + appBar: AppBar(
20 + iconTheme: IconThemeData(color: Colors.black),
21 + backgroundColor: Colors.white,
22 + title: Text(
23 + 'Smart Medicine Box',
24 + style: TextStyle(
25 + color: Colors.black,
26 + fontSize: 20,
27 + fontFamily: 'Noto',
28 + fontWeight: FontWeight.bold),
29 + ),
30 + actions: [
31 + IconButton(
32 + icon: Icon(
33 + Icons.settings,
34 + color: Colors.black,
35 + ),
36 + onPressed: () {},
37 + )
38 + ],
39 + ),
40 + drawer: Drawer(
41 + child: ListView(
42 + children: [
43 + DrawerHeader(
44 + child: Text('Drawer Header'),
45 + decoration: BoxDecoration(
46 + color: Colors.blue,
47 + ),
48 + ),
49 + ListTile(
50 + title: Text('Test 1'),
51 + onTap: () {},
52 + ),
53 + ListTile(
54 + title: Text('Test 2'),
55 + onTap: () {},
56 + ),
57 + ListTile(
58 + title: Text('Test 3'),
59 + onTap: () {},
60 + ),
61 + ],
62 + ),
63 + ),
64 + body: Container(
65 + height: size.height * 0.9,
66 + margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
67 + padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
68 + child: Column(
69 + children: <Widget>[
70 + Container(
71 + padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
72 + height: size.height * 0.08,
73 + width: size.width,
74 + child: Center(
75 + child: Text(
76 + 'Setting',
77 + textAlign: TextAlign.center,
78 + textScaleFactor: 1.0,
79 + style: TextStyle(
80 + color: Colors.black,
81 + fontSize: 32,
82 + fontFamily: 'NotoSansKR',
83 + fontWeight: FontWeight.w700),
84 + ),
85 + ),
86 + ),
87 + Container(
88 + height: size.height * 0.6,
89 + child: Column(
90 + crossAxisAlignment: CrossAxisAlignment.center,
91 + children: <Widget>[
92 + Container(
93 + padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
94 + width: size.width * 0.8,
95 + height: size.height * 0.13,
96 + margin: EdgeInsets.only(bottom: 0),
97 + child: FlatButton(
98 + height: size.height * 0.07,
99 + onPressed: () {
100 + Navigator.push(
101 + context,
102 + MaterialPageRoute(
103 + builder: (BuildContext context) => Alarm(),
104 + ));
105 + },
106 + child: Text(
107 + '알림 설정',
108 + textScaleFactor: 1.0,
109 + style: TextStyle(
110 + color: Colors.white,
111 + fontSize: 24,
112 + fontFamily: 'Noto',
113 + fontWeight: FontWeight.bold),
114 + ),
115 + color: Color(0xff0B1E33),
116 + shape: RoundedRectangleBorder(
117 + borderRadius: BorderRadius.circular(50)),
118 + ),
119 + ),
120 + Container(
121 + padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
122 + width: size.width * 0.8,
123 + height: size.height * 0.13,
124 + margin: EdgeInsets.only(bottom: 0),
125 + child: FlatButton(
126 + height: size.height * 0.07,
127 + onPressed: () {
128 + Navigator.push(
129 + context,
130 + MaterialPageRoute(
131 + builder: (BuildContext context) =>
132 + HubModifyList(),
133 + ));
134 + },
135 + child: Text(
136 + '허브 관리',
137 + textScaleFactor: 1.0,
138 + style: TextStyle(
139 + color: Colors.white,
140 + fontSize: 24,
141 + fontFamily: 'Noto',
142 + fontWeight: FontWeight.bold),
143 + ),
144 + color: Color(0xff0B1E33),
145 + shape: RoundedRectangleBorder(
146 + borderRadius: BorderRadius.circular(50)),
147 + ),
148 + ),
149 + Container(
150 + padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
151 + width: size.width * 0.8,
152 + height: size.height * 0.13,
153 + margin: EdgeInsets.only(bottom: 0),
154 + child: FlatButton(
155 + height: size.height * 0.07,
156 + onPressed: () {
157 + Navigator.push(
158 + context,
159 + MaterialPageRoute(
160 + builder: (BuildContext context) =>
161 + BottleModifyList(),
162 + ));
163 + },
164 + child: Text(
165 + '약병 관리',
166 + textScaleFactor: 1.0,
167 + style: TextStyle(
168 + color: Colors.white,
169 + fontSize: 24,
170 + fontFamily: 'Noto',
171 + fontWeight: FontWeight.bold),
172 + ),
173 + color: Color(0xff0B1E33),
174 + shape: RoundedRectangleBorder(
175 + borderRadius: BorderRadius.circular(50)),
176 + ),
177 + ),
178 + ],
179 + ),
180 + ),
181 + ],
182 + ),
183 + ),
184 + bottomNavigationBar: BottomNavigationBar(
185 + type: BottomNavigationBarType.fixed,
186 + backgroundColor: Colors.grey,
187 + selectedItemColor: Colors.white.withOpacity(.60),
188 + unselectedItemColor: Colors.white.withOpacity(.60),
189 + selectedFontSize: 14,
190 + unselectedFontSize: 14,
191 + currentIndex: 0,
192 + onTap: (int index) => {
193 + setState(
194 + () {
195 + Navigator.push(
196 + context,
197 + MaterialPageRoute(
198 + builder: (BuildContext context) =>
199 + DashBoard(pageNumber: index),
200 + ),
201 + );
202 + },
203 + )
204 + },
205 + items: [
206 + BottomNavigationBarItem(
207 + icon: Icon(Icons.device_thermostat), label: 'In'),
208 + BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
209 + BottomNavigationBarItem(
210 + label: 'Out',
211 + icon: Icon(Icons.access_time),
212 + )
213 + ],
214 + ),
215 + ),
216 + );
217 + }
218 +}
1 +import 'package:flutter/material.dart';
2 +import 'package:rxdart/subjects.dart';
3 +import 'package:shared_preferences/shared_preferences.dart';
4 +import 'package:flutter/cupertino.dart';
5 +import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
6 +import 'package:flutter_local_notifications/flutter_local_notifications.dart';
7 +import 'package:Smart_Medicine_Box/src/screens/SettingPage.dart';
8 +import 'package:Smart_Medicine_Box/src/screens/SettingPage/customTimepicker.dart';
9 +
10 +final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
11 + FlutterLocalNotificationsPlugin();
12 +// Streams are created so that app can respond to notification-related events since the plugin is initialised in the `main` function
13 +final BehaviorSubject<ReceivedNotification> didReceiveLocalNotificationSubject =
14 + BehaviorSubject<ReceivedNotification>();
15 +
16 +final BehaviorSubject<String> selectNotificationSubject =
17 + BehaviorSubject<String>();
18 +
19 +NotificationAppLaunchDetails notificationAppLaunchDetails;
20 +
21 +class ReceivedNotification {
22 + final int id;
23 + final String title;
24 + final String body;
25 + final String payload;
26 +
27 + ReceivedNotification({
28 + @required this.id,
29 + @required this.title,
30 + @required this.body,
31 + @required this.payload,
32 + });
33 +}
34 +
35 +class Alarm extends StatefulWidget {
36 + @override
37 + _AlarmnState createState() => _AlarmnState();
38 +}
39 +
40 +class _AlarmnState extends State<Alarm> {
41 + FlutterLocalNotificationsPlugin fltrNotification;
42 +
43 + List<Widget> alarmList = [];
44 + List<dynamic> weekdays = [];
45 + List<String> times = [];
46 + List<int> timesHours = [];
47 + List<int> timesMinutes = [];
48 + List<dynamic> saveIndex = [];
49 + List<dynamic> isSwitched = [];
50 + List<bool> _weekday = [false, false, false, false, false, false, false];
51 +
52 + void initState() {
53 + super.initState();
54 + main();
55 + }
56 +
57 + Future<void> main() async {
58 + // needed if you intend to initialize in the `main` function
59 + WidgetsFlutterBinding.ensureInitialized();
60 + // NOTE: if you want to find out if the app was launched via notification then you could use the following call and then do something like
61 + // change the default route of the app
62 + // var notificationAppLaunchDetails =
63 + // await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
64 +
65 + var initializationSettingsAndroid =
66 + new AndroidInitializationSettings('app_icon');
67 + var initializationSettingsIOS = IOSInitializationSettings(
68 + requestAlertPermission: true,
69 + requestBadgePermission: true,
70 + requestSoundPermission: true,
71 + onDidReceiveLocalNotification:
72 + (int id, String title, String body, String payload) async {});
73 + var initializationSettings = InitializationSettings(
74 + initializationSettingsAndroid, initializationSettingsIOS);
75 + await flutterLocalNotificationsPlugin.initialize(initializationSettings,
76 + onSelectNotification: (String payload) async {
77 + if (payload != null) {
78 + debugPrint('notification payload: ' + payload);
79 + }
80 + });
81 + }
82 +
83 + void _requestIOSPermissions() {
84 + flutterLocalNotificationsPlugin
85 + .resolvePlatformSpecificImplementation<
86 + IOSFlutterLocalNotificationsPlugin>()
87 + ?.requestPermissions(
88 + alert: true,
89 + badge: true,
90 + sound: true,
91 + );
92 + }
93 +
94 + void insertAlarm() {
95 + setState(() {
96 + weekdays.add([false, false, false, false, false, false, false]);
97 + times.add(' ');
98 + timesHours.add(0);
99 + timesMinutes.add(0);
100 + isSwitched.add(false);
101 +
102 + var length = saveIndex.length;
103 +
104 + if (saveIndex.length == 0) {
105 + saveIndex.add(1);
106 + } else {
107 + saveIndex.add(saveIndex[length - 1] + 1);
108 + }
109 +
110 + length = saveIndex.length;
111 + /*
112 + _prefs.setString('alarmList', weekdays.toString());
113 + for (var i = 0; i < times.length; i++) {
114 + _prefs.setString('time' + (saveIndex[i]).toString(),
115 + '${timesHours[i]}:${timesMinutes[i]}');
116 + }
117 + _prefs.setString('timeIndex', saveIndex.toString());
118 + _prefs.setString('toggle', isSwitched.toString());
119 +*/
120 + print(saveIndex);
121 + });
122 + }
123 +
124 + void rerendering() {
125 + print(weekdays);
126 + print(times);
127 + print(timesHours);
128 + print(timesMinutes);
129 + setState(() {});
130 + }
131 +
132 + void _configureDidReceiveLocalNotificationSubject() {
133 + didReceiveLocalNotificationSubject.stream
134 + .listen((ReceivedNotification receivedNotification) async {
135 + await showDialog(
136 + context: context,
137 + builder: (BuildContext context) => CupertinoAlertDialog(
138 + title: receivedNotification.title != null
139 + ? Text(receivedNotification.title)
140 + : null,
141 + content: receivedNotification.body != null
142 + ? Text(receivedNotification.body)
143 + : null,
144 + actions: [
145 + CupertinoDialogAction(
146 + isDefaultAction: true,
147 + child: Text('Ok'),
148 + onPressed: () async {
149 + Navigator.of(context, rootNavigator: true).pop();
150 + await Navigator.push(
151 + context,
152 + MaterialPageRoute(
153 + builder: (context) =>
154 + SecondScreen(receivedNotification.payload),
155 + ),
156 + );
157 + },
158 + )
159 + ],
160 + ),
161 + );
162 + });
163 + }
164 +
165 + void _configureSelectNotificationSubject() {
166 + selectNotificationSubject.stream.listen((String payload) async {
167 + await Navigator.push(
168 + context,
169 + MaterialPageRoute(builder: (context) => SecondScreen(payload)),
170 + );
171 + });
172 + }
173 +
174 + @override
175 + void dispose() {
176 + didReceiveLocalNotificationSubject.close();
177 + selectNotificationSubject.close();
178 + super.dispose();
179 + }
180 +
181 + Widget build(BuildContext context) {
182 + final Size size = MediaQuery.of(context).size;
183 + return MaterialApp(
184 + title: 'Welcome to Flutter',
185 + home: Scaffold(
186 + appBar: AppBar(
187 + iconTheme: IconThemeData(color: Colors.black),
188 + backgroundColor: Colors.white,
189 + title: Text(
190 + 'Smart Medicine Box',
191 + style: TextStyle(
192 + color: Colors.black,
193 + fontSize: 20,
194 + fontFamily: 'Noto',
195 + fontWeight: FontWeight.bold),
196 + ),
197 + actions: [
198 + IconButton(
199 + icon: Icon(
200 + Icons.settings,
201 + color: Colors.black,
202 + ),
203 + onPressed: () {
204 + Navigator.push(
205 + context,
206 + MaterialPageRoute(
207 + builder: (BuildContext context) => SettingPage(),
208 + ));
209 + },
210 + )
211 + ],
212 + ),
213 + drawer: Drawer(
214 + child: ListView(
215 + children: [
216 + DrawerHeader(
217 + child: Text('Drawer Header'),
218 + decoration: BoxDecoration(
219 + color: Colors.blue,
220 + ),
221 + ),
222 + ListTile(
223 + title: Text('Test 1'),
224 + onTap: () {},
225 + ),
226 + ListTile(
227 + title: Text('Test 2'),
228 + onTap: () {},
229 + ),
230 + ListTile(
231 + title: Text('Test 3'),
232 + onTap: () {},
233 + ),
234 + ],
235 + ),
236 + ),
237 + body: SingleChildScrollView(
238 + scrollDirection: Axis.vertical,
239 + child: Padding(
240 + padding: EdgeInsets.all(8.0),
241 + child: Column(
242 + crossAxisAlignment: CrossAxisAlignment.center,
243 + children: <Widget>[
244 + Row(
245 + mainAxisAlignment: MainAxisAlignment.center,
246 + children: <Widget>[
247 + Container(
248 + width: 180,
249 + height: 80,
250 + padding: const EdgeInsets.all(20.0),
251 + child: RaisedButton(
252 + onPressed: () async {
253 + insertAlarm();
254 + },
255 + shape: RoundedRectangleBorder(
256 + borderRadius: new BorderRadius.circular(30.0),
257 + side: BorderSide(color: Colors.blue)),
258 + color: Color(0xff1674f6),
259 + child: Text(
260 + '알람 추가',
261 + textScaleFactor: 1.0,
262 + style: TextStyle(
263 + fontSize: 16,
264 + color: Colors.white,
265 + fontWeight: FontWeight.bold),
266 + ),
267 + ),
268 + ),
269 + ],
270 + ),
271 + for (var i = 0; i < weekdays.length; i++)
272 + inAlarmData(
273 + context,
274 + weekdays,
275 + weekdays[i],
276 + _showWeeklyAtDayAndTime,
277 + times[i],
278 + timesHours[i],
279 + timesMinutes[i],
280 + i + 1,
281 + rerendering,
282 + size,
283 + )
284 + ],
285 + ),
286 + ),
287 + ),
288 + ),
289 + );
290 + }
291 +
292 + Widget inAlarmData(
293 + BuildContext context,
294 + var allweekddata,
295 + var weekdayArray,
296 + var activeFunctions,
297 + var timeString,
298 + var timeHour,
299 + var timesMinite,
300 + var index,
301 + var rerendering,
302 + Size size,
303 + ) {
304 + SharedPreferences _prefs;
305 +
306 + var savetimeStrings;
307 + var setDaysString = ['월', '화', '수', '목', '금', '토', '일'];
308 +
309 + return Container(
310 + margin: EdgeInsets.fromLTRB(0, 0, 0, 20),
311 + decoration: BoxDecoration(
312 + border: Border.all(
313 + color: Color(0xffd0d0d0),
314 + ),
315 + borderRadius: BorderRadius.all(Radius.circular(5)),
316 + ),
317 + child: Column(
318 + children: <Widget>[
319 + Container(
320 + alignment: Alignment.center,
321 + width: size.width,
322 + height: 50.0,
323 + child: Row(
324 + mainAxisAlignment: MainAxisAlignment.center,
325 + children: <Widget>[
326 + Row(
327 + mainAxisAlignment: MainAxisAlignment.center,
328 + children: <Widget>[
329 + for (var i = 0; i < weekdayArray.length; i++)
330 + GestureDetector(
331 + onTap: () async {
332 + _prefs = await SharedPreferences.getInstance();
333 +
334 + if (weekdayArray[i] == false) {
335 + weekdayArray[i] = true;
336 + } else {
337 + weekdayArray[i] = false;
338 + }
339 +
340 + _prefs.setString(
341 + 'alarmList', allweekddata.toString());
342 +
343 + rerendering();
344 + },
345 + child: Container(
346 + margin: EdgeInsets.fromLTRB(15, 0, 0, 0),
347 + width: size.width * 0.09,
348 + child: Text(
349 + setDaysString[i],
350 + style: TextStyle(
351 + color: weekdayArray[i] == false
352 + ? Colors.teal
353 + : Colors.red,
354 + fontWeight: FontWeight.bold,
355 + fontSize: 20.0),
356 + )),
357 + ),
358 + ],
359 + )
360 + ],
361 + ),
362 + color: Colors.white,
363 + ),
364 + RaisedButton(
365 + shape: RoundedRectangleBorder(
366 + borderRadius: BorderRadius.circular(5.0)),
367 + elevation: 4.0,
368 + onPressed: () async {
369 + _prefs = await SharedPreferences.getInstance();
370 + var abc = await DatePicker.showPicker(
371 + context,
372 + theme: DatePickerTheme(
373 + containerHeight: 210.0,
374 + ),
375 + showTitleActions: true,
376 + onConfirm: (time) {
377 + print('confirm $time');
378 +
379 + // realTime = new DateTime(time.hour, time.minute);
380 + timeHour = time.hour;
381 + timesMinite = time.minute;
382 +
383 + savetimeStrings = '${time.hour}:${time.minute}';
384 +
385 + var minutString;
386 +
387 + if (timesMinite.toString().length == 1) {
388 + minutString = '0' + timesMinite.toString();
389 + } else {
390 + minutString = timesMinite.toString();
391 + }
392 +
393 + if (timeHour - 12 < 0) {
394 + timeString = '오전 ${time.hour}:' + minutString;
395 + } else {
396 + if (timeHour == 12) {
397 + timeString = '오후 ${time.hour}:' + minutString;
398 + } else {
399 + timeString = '오후 ${time.hour - 12}:' + minutString;
400 + }
401 + }
402 + },
403 + pickerModel: CustomPicker(
404 + currentTime: DateTime.now(), locale: LocaleType.ko),
405 + );
406 +
407 + times[index - 1] = timeString;
408 + timesHours[index - 1] = timeHour;
409 + timesMinutes[index - 1] = timesMinite;
410 +
411 + _prefs.setString('time' + (saveIndex[index - 1]).toString(),
412 + savetimeStrings);
413 +
414 + print(savetimeStrings);
415 +
416 + setState(() {
417 + savetimeStrings = savetimeStrings;
418 + });
419 + // rerendering();
420 + },
421 + child: Container(
422 + alignment: Alignment.center,
423 + height: 50.0,
424 + child: Row(
425 + mainAxisAlignment: MainAxisAlignment.center,
426 + children: <Widget>[
427 + Row(
428 + mainAxisAlignment: MainAxisAlignment.center,
429 + children: <Widget>[
430 + Container(
431 + child: Row(
432 + mainAxisAlignment: MainAxisAlignment.center,
433 + children: <Widget>[
434 + Icon(
435 + Icons.access_time,
436 + size: 18.0,
437 + color: Colors.teal,
438 + ),
439 + Text(
440 + " " + timeString,
441 + textAlign: TextAlign.center,
442 + style: TextStyle(
443 + color: Colors.teal,
444 + fontWeight: FontWeight.bold,
445 + fontSize: 18.0),
446 + ),
447 + ],
448 + ),
449 + )
450 + ],
451 + ),
452 + ],
453 + ),
454 + ),
455 + color: Colors.white,
456 + ),
457 + Container(
458 + padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
459 + decoration: BoxDecoration(
460 + borderRadius: BorderRadius.circular(5.0),
461 + color: Colors.white),
462 + child: Container(
463 + alignment: Alignment.center,
464 + height: 50.0,
465 + child: Row(
466 + mainAxisAlignment: MainAxisAlignment.spaceBetween,
467 + children: <Widget>[
468 + Text(
469 + "알람 설정",
470 + style: TextStyle(
471 + color: Colors.teal,
472 + fontWeight: FontWeight.bold,
473 + fontSize: 18.0),
474 + ),
475 + Switch(
476 + value: isSwitched[index - 1],
477 + onChanged: (value) async {
478 + print(savetimeStrings);
479 + if (value == true) {
480 + _prefs = await SharedPreferences.getInstance();
481 + int count = 1;
482 + bool allDayFalse = true;
483 + for (var i = 0; i < weekdayArray.length; i++) {
484 + if (weekdayArray[i] == true) {
485 + await activeFunctions(timeHour, timesMinite,
486 + i + 1, index * 10, count);
487 + count++;
488 + allDayFalse = false;
489 + }
490 + }
491 + if (allDayFalse == true) {
492 + showDialog(
493 + context: context,
494 + builder: (BuildContext context) {
495 + return AlertDialog(
496 + title: new Text('요일 선택 오류'),
497 + content:
498 + new Text('선택된 요일이 없습니다. 요일을 선택해주세요.'),
499 + actions: <Widget>[
500 + new FlatButton(
501 + child: new Text('닫기'),
502 + onPressed: () {
503 + Navigator.of(context).pop();
504 + })
505 + ],
506 + );
507 + });
508 + } else if (_prefs.getString('time' +
509 + (saveIndex[index - 1]).toString()) ==
510 + null) {
511 + showDialog(
512 + context: context,
513 + builder: (BuildContext context) {
514 + return AlertDialog(
515 + title: new Text('시간 설정 오류'),
516 + content:
517 + new Text('설정된 시간이 없습니다. 시간을 설정해주세요.'),
518 + actions: <Widget>[
519 + new FlatButton(
520 + child: new Text('닫기'),
521 + onPressed: () {
522 + Navigator.of(context).pop();
523 + })
524 + ],
525 + );
526 + });
527 + } else {
528 + setState(() {
529 + print(value);
530 + isSwitched[index - 1] = value;
531 + _prefs.setString(
532 + 'alarmList', allweekddata.toString());
533 + // _prefs.setString(
534 + // 'time' + saveIndex[index - 1].toString(),
535 + // savetimeStrings);
536 + _prefs.setString(
537 + 'timeIndex', saveIndex.toString());
538 + _prefs.setString(
539 + 'toggle', isSwitched.toString());
540 + print('time' + index.toString());
541 + showDialog(
542 + context: context,
543 + builder: (BuildContext context) {
544 + return AlertDialog(
545 + title: new Text('알람'),
546 + content: new Text('알람 설정을 완료 하였습니다.'),
547 + actions: <Widget>[
548 + new FlatButton(
549 + child: new Text('확인'),
550 + onPressed: () {
551 + Navigator.of(context).pop();
552 + })
553 + ],
554 + );
555 + });
556 + });
557 + }
558 + } else {
559 + _prefs = await SharedPreferences.getInstance();
560 + int count = 1;
561 + for (var i = 0; i < weekdayArray.length; i++) {
562 + if (weekdayArray[i] == true) {
563 + await flutterLocalNotificationsPlugin
564 + .cancel((index * 10) + count);
565 + count++;
566 + }
567 + }
568 + setState(() {
569 + isSwitched[index - 1] = value;
570 + _prefs.setString('toggle', isSwitched.toString());
571 + });
572 + }
573 + }),
574 + GestureDetector(
575 + onTap: () async {
576 + showDialog(
577 + context: context,
578 + builder: (BuildContext context) {
579 + return AlertDialog(
580 + title: new Text('알람 삭제'),
581 + content: new Text('선택한 알람을 삭제하시겠습니까?'),
582 + actions: <Widget>[
583 + new FlatButton(
584 + child: new Text('취소'),
585 + onPressed: () {
586 + Navigator.of(context).pop();
587 + }),
588 + new FlatButton(
589 + child: new Text('삭제'),
590 + onPressed: () async {
591 + _prefs = await SharedPreferences
592 + .getInstance();
593 + int count = 1;
594 + for (var i = 0;
595 + i < weekdayArray.length;
596 + i++) {
597 + if (weekdayArray[i] == true) {
598 + await flutterLocalNotificationsPlugin
599 + .cancel((index * 10) + count);
600 + count++;
601 + }
602 + }
603 + print(saveIndex);
604 + allweekddata.removeAt(index - 1);
605 + _prefs.remove('time' +
606 + saveIndex[index - 1].toString());
607 + times.removeAt(index - 1);
608 + saveIndex.removeAt(index - 1);
609 + isSwitched.removeAt(index - 1);
610 + _prefs.setString('alarmList',
611 + allweekddata.toString());
612 + _prefs.setString('timeIndex',
613 + saveIndex.toString());
614 + _prefs.setString(
615 + 'toggle', isSwitched.toString());
616 + rerendering();
617 + Navigator.of(context).pop();
618 + })
619 + ],
620 + );
621 + });
622 + },
623 + child: Icon(
624 + Icons.close,
625 + ))
626 + ],
627 + ),
628 + ),
629 + ),
630 + ],
631 + ));
632 + }
633 +
634 + /// weekday 가 1부터 7순으로 일 월 화 수 목 금 토 일 순서로 구성이 되어 있음 이에 따라 설정한 Weekday time 에 학습 알람을 뛰어주는 역할을 해주는 함수
635 + Future<void> _showWeeklyAtDayAndTime(
636 + int a, int b, int weekday, int index, int idindex) async {
637 + Day setDay;
638 +
639 + if (weekday == 1) {
640 + setDay = Day.Monday;
641 + } else if (weekday == 2) {
642 + setDay = Day.Tuesday;
643 + } else if (weekday == 3) {
644 + setDay = Day.Wednesday;
645 + } else if (weekday == 4) {
646 + setDay = Day.Thursday;
647 + } else if (weekday == 5) {
648 + setDay = Day.Friday;
649 + } else if (weekday == 6) {
650 + setDay = Day.Saturday;
651 + } else if (weekday == 7) {
652 + setDay = Day.Sunday;
653 + }
654 + print('dd');
655 +
656 + var time = Time(a, b, 0);
657 + var androidPlatformChannelSpecifics = AndroidNotificationDetails(
658 + 'show weekly channel id',
659 + 'show weekly channel name',
660 + 'show weekly description');
661 + var iOSPlatformChannelSpecifics = IOSNotificationDetails();
662 + var platformChannelSpecifics = NotificationDetails(
663 + androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
664 + await flutterLocalNotificationsPlugin.showWeeklyAtDayAndTime(
665 + index + idindex,
666 + '약통 알람 ',
667 + '알약 섭취 시간인 ${_toTwoDigitString(time.hour)}:${_toTwoDigitString(time.minute)}이 되었습니다.',
668 + setDay,
669 + time,
670 + platformChannelSpecifics);
671 + }
672 +
673 + String _toTwoDigitString(int value) {
674 + return value.toString().padLeft(2, '0');
675 + }
676 +
677 + Future<void> onDidReceiveLocalNotification(
678 + int id, String title, String body, String payload) async {
679 + // display a dialog with the notification details, tap ok to go to another page
680 + await showDialog(
681 + context: context,
682 + builder: (BuildContext context) => CupertinoAlertDialog(
683 + title: title != null ? Text(title) : null,
684 + content: body != null ? Text(body) : null,
685 + actions: [
686 + CupertinoDialogAction(
687 + isDefaultAction: true,
688 + child: Text('Ok'),
689 + onPressed: () async {
690 + Navigator.of(context, rootNavigator: true).pop();
691 + await Navigator.push(
692 + context,
693 + MaterialPageRoute(
694 + builder: (context) => SecondScreen(payload),
695 + ),
696 + );
697 + },
698 + )
699 + ],
700 + ),
701 + );
702 + }
703 +}
704 +
705 +class SecondScreen extends StatefulWidget {
706 + SecondScreen(this.payload);
707 +
708 + final String payload;
709 +
710 + @override
711 + State<StatefulWidget> createState() => SecondScreenState();
712 +}
713 +
714 +class SecondScreenState extends State<SecondScreen> {
715 + String _payload;
716 + @override
717 + void initState() {
718 + super.initState();
719 + _payload = widget.payload;
720 + }
721 +
722 + @override
723 + Widget build(BuildContext context) {
724 + return Scaffold(
725 + appBar: AppBar(
726 + title: Text('Second Screen with payload: ${(_payload ?? '')}'),
727 + ),
728 + body: Center(
729 + child: RaisedButton(
730 + onPressed: () {
731 + Navigator.pop(context);
732 + },
733 + child: Text('Go back!'),
734 + ),
735 + ),
736 + );
737 + }
738 +}
1 +import 'dart:convert';
2 +import 'package:Smart_Medicine_Box/src/screens/Register/RegisterBottle.dart';
3 +import 'package:flutter/material.dart';
4 +import 'package:flutter/services.dart';
5 +import 'package:http/http.dart' as http;
6 +import 'package:flutter_dotenv/flutter_dotenv.dart';
7 +import '../models/Bottle.dart';
8 +import '../../utils/user_secure_stoarge.dart';
9 +
10 +class BottleModifyList extends StatefulWidget {
11 + BottleModifyList({Key key}) : super(key: key);
12 +
13 + @override
14 + _BottleModifyListState createState() => _BottleModifyListState();
15 +}
16 +
17 +class _BottleModifyListState extends State<BottleModifyList> {
18 + List<Bottle> _bottleList = new List<Bottle>();
19 + Future<String> getBottleList() async {
20 + String hubid = await UserSecureStorage.getHubId();
21 + String usertoken = await UserSecureStorage.getUserToken();
22 +
23 + http.Response response = await http.get(
24 + Uri.encodeFull(
25 + DotEnv().env['SERVER_URL'] + 'bottle/hub/' + hubid.toString()),
26 + headers: {"authorization": usertoken},
27 + );
28 +
29 + if (_bottleList.length != 0) {
30 + _bottleList.clear();
31 + }
32 + if (response.statusCode == 200) {
33 + List<dynamic> values = new List<dynamic>();
34 + values = json.decode(response.body);
35 +
36 + for (int i = 0; i < values.length; i++) {
37 + Map<String, dynamic> map = values[i];
38 + _bottleList.add(Bottle.fromJson(map));
39 + }
40 +
41 + return "GET";
42 + } else if (response.statusCode == 404) {
43 + return "Not Found";
44 + } else {
45 + return "Error";
46 + }
47 + }
48 +
49 + Future<String> deleteBottle(int index) async {
50 + String usertoken = await UserSecureStorage.getUserToken();
51 + http.Response response = await http.delete(
52 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle/' + index.toString()),
53 + headers: {"authorization": usertoken},
54 + );
55 + print('asdgasdga');
56 + print(response.statusCode);
57 + if (response.statusCode == 204) {
58 + return "Delete";
59 + } else {
60 + return "Error";
61 + }
62 + }
63 +
64 + Widget build(BuildContext context) {
65 + final Size size = MediaQuery.of(context).size;
66 + return Scaffold(
67 + appBar: AppBar(
68 + backgroundColor: Colors.white,
69 + leading: new Icon(Icons.medical_services_rounded,
70 + color: Colors.black, size: 45.0),
71 + title: Text(
72 + 'Smart Medicine Box',
73 + style: TextStyle(
74 + color: Colors.black,
75 + fontSize: 23,
76 + fontFamily: 'Noto',
77 + fontWeight: FontWeight.bold),
78 + ),
79 + ),
80 + body: FutureBuilder(
81 + future: getBottleList(),
82 + builder: (BuildContext context, AsyncSnapshot snapshot) {
83 + if (snapshot.hasData == false) {
84 + return CircularProgressIndicator();
85 + } else if (snapshot.hasError) {
86 + return Padding(
87 + padding: const EdgeInsets.all(8.0),
88 + child: Text(
89 + 'Error: ${snapshot.error}',
90 + style: TextStyle(fontSize: 15),
91 + ),
92 + );
93 + } else {
94 + return Container(
95 + height: size.height,
96 + child: Column(
97 + mainAxisAlignment: MainAxisAlignment.center,
98 + children: <Widget>[
99 + SizedBox(height: 10),
100 + Container(
101 + height: size.height * 0.07,
102 + width: size.width,
103 + child: Center(
104 + child: Text(
105 + '등록된 약병 리스트',
106 + textScaleFactor: 1.0,
107 + style: TextStyle(
108 + fontSize: 28,
109 + fontFamily: 'Noto',
110 + fontWeight: FontWeight.bold),
111 + ),
112 + ),
113 + ),
114 + SizedBox(height: 10),
115 + Expanded(
116 + child: GridView.builder(
117 + padding: const EdgeInsets.all(30),
118 + itemCount:
119 + _bottleList.length == null ? 0 : _bottleList.length,
120 + gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
121 + maxCrossAxisExtent: 200,
122 + crossAxisSpacing: 10,
123 + mainAxisSpacing: 10,
124 + ),
125 + itemBuilder: (BuildContext context, int index) {
126 + return InkResponse(
127 + splashColor: Colors.transparent,
128 + child: Container(
129 + height: 140,
130 + padding: const EdgeInsets.all(10),
131 + decoration: BoxDecoration(
132 + border: Border.all(),
133 + borderRadius: BorderRadius.all(
134 + Radius.circular(16.0),
135 + ),
136 + ),
137 + child: Column(
138 + children: [
139 + Container(
140 + decoration: BoxDecoration(
141 + border: Border(
142 + bottom: BorderSide(
143 + color: Colors.black,
144 + width: 1,
145 + style: BorderStyle.solid),
146 + ),
147 + ),
148 + height: 40,
149 + child: Row(
150 + mainAxisAlignment:
151 + MainAxisAlignment.spaceBetween,
152 + children: [
153 + Container(
154 + height: 40,
155 + child: Center(
156 + child: Text(
157 + '${_bottleList[index].bottleId}',
158 + style: TextStyle(
159 + color: Colors.black,
160 + fontSize: 20,
161 + fontFamily: 'Noto',
162 + fontWeight: FontWeight.bold),
163 + ),
164 + ),
165 + ),
166 + Container(
167 + child: IconButton(
168 + alignment: Alignment(0.9, 0),
169 + icon: Icon(
170 + Icons.create_sharp,
171 + color: Colors.black,
172 + ),
173 + onPressed: () {},
174 + ),
175 + ),
176 + ],
177 + ),
178 + ),
179 + SizedBox(height: 10),
180 + Container(
181 + height: 90,
182 + child: Icon(
183 + Icons.medical_services_outlined,
184 + size: 100,
185 + ),
186 + )
187 + ],
188 + ),
189 + ),
190 + onTap: () {
191 + if (_bottleList.length == 1) {
192 + showDialog(
193 + context: context,
194 + builder: (BuildContext context) {
195 + return AlertDialog(
196 + title: new Text('약병 삭제'),
197 + content:
198 + new Text('등록된 약병이 하나이므로 해제가 불가능 합니다.'),
199 + actions: <Widget>[
200 + new FlatButton(
201 + child: new Text('Cloes'),
202 + onPressed: () {
203 + Navigator.of(context).pop();
204 + }),
205 + ],
206 + );
207 + },
208 + );
209 + } else {
210 + showDialog(
211 + context: context,
212 + builder: (BuildContext context) {
213 + return AlertDialog(
214 + title: new Text('약병 삭제'),
215 + content: new Text(
216 + _bottleList[index].bottleId.toString() +
217 + '을 삭제 하시겠습니까?'),
218 + actions: <Widget>[
219 + new FlatButton(
220 + child: new Text('삭제'),
221 + onPressed: () async {
222 + print('dfg');
223 + await deleteBottle(
224 + _bottleList[index].bottleId);
225 + setState(() {});
226 + Navigator.of(context).pop();
227 + },
228 + ),
229 + new FlatButton(
230 + child: new Text('취소'),
231 + onPressed: () {
232 + Navigator.of(context).pop();
233 + },
234 + )
235 + ],
236 + );
237 + },
238 + );
239 + }
240 + },
241 + );
242 + },
243 + ),
244 + ),
245 + Container(
246 + padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
247 + width: size.width * 0.8,
248 + height: size.height * 0.13,
249 + margin: EdgeInsets.only(bottom: 0),
250 + child: FlatButton(
251 + height: size.height * 0.06,
252 + onPressed: () async {
253 + await Navigator.push(
254 + context,
255 + MaterialPageRoute(
256 + builder: (BuildContext context) =>
257 + RegisterBottle(modify_bottle: true),
258 + ),
259 + );
260 + setState(() {});
261 + },
262 + child: Text(
263 + '약병 추가',
264 + textScaleFactor: 1.0,
265 + style: TextStyle(
266 + color: Colors.white,
267 + fontSize: 24,
268 + fontFamily: 'Noto',
269 + fontWeight: FontWeight.bold),
270 + ),
271 + color: Color(0xff0B1E33),
272 + shape: RoundedRectangleBorder(
273 + borderRadius: BorderRadius.circular(50)),
274 + ),
275 + ),
276 + ],
277 + ),
278 + );
279 + }
280 + },
281 + ),
282 + );
283 + }
284 +}
1 +import 'package:flutter/material.dart';
2 +
3 +import 'package:Smart_Medicine_Box/src/screens/SettingPage.dart';
4 +
5 +class DEVInformation extends StatefulWidget {
6 + @override
7 + _DEVInformationState createState() => _DEVInformationState();
8 +}
9 +
10 +class _DEVInformationState extends State<DEVInformation> {
11 + Widget build(BuildContext context) {
12 + final Size size = MediaQuery.of(context).size;
13 + return Scaffold(
14 + appBar: AppBar(
15 + iconTheme: IconThemeData(color: Colors.black),
16 + backgroundColor: Colors.white,
17 + title: Text(
18 + 'Smart Medicine Box',
19 + style: TextStyle(
20 + color: Colors.black,
21 + fontSize: 20,
22 + fontFamily: 'Noto',
23 + fontWeight: FontWeight.bold),
24 + ),
25 + actions: [
26 + IconButton(
27 + icon: Icon(
28 + Icons.settings,
29 + color: Colors.black,
30 + ),
31 + onPressed: () {
32 + Navigator.push(
33 + context,
34 + MaterialPageRoute(
35 + builder: (BuildContext context) => SettingPage(),
36 + ));
37 + },
38 + )
39 + ],
40 + ),
41 + body: Text('1234'),
42 + );
43 + }
44 +}
1 +import 'package:Smart_Medicine_Box/src/screens/Register/RegsiterHub.dart';
2 +import 'package:flutter/cupertino.dart';
3 +import 'package:flutter/material.dart';
4 +import 'dart:convert';
5 +import 'package:http/http.dart' as http;
6 +import 'package:flutter_dotenv/flutter_dotenv.dart';
7 +// Screen import
8 +import '../../utils/user_secure_stoarge.dart';
9 +
10 +class HubModifyList extends StatefulWidget {
11 + List<int> hublist;
12 + HubModifyList({Key key, this.hublist}) : super(key: key);
13 +
14 + @override
15 + _HubModifyListState createState() => _HubModifyListState();
16 +}
17 +
18 +class _HubModifyListState extends State<HubModifyList> {
19 + List<int> _hublist = new List<int>();
20 + //Get Hub List 함수
21 + Future<String> getHubList() async {
22 + String usertoken = await UserSecureStorage.getUserToken();
23 + http.Response response = await http.get(
24 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'),
25 + headers: {"authorization": usertoken},
26 + );
27 + List<dynamic> values = new List<dynamic>();
28 + if (_hublist.length != 0) {
29 + _hublist.clear();
30 + }
31 + if (response.statusCode == 200) {
32 + values = json.decode(response.body);
33 + for (int i = 0; i < values.length; i++) {
34 + _hublist.add(values[i]['hubId']);
35 + }
36 + print(_hublist);
37 + return "get완료";
38 + } else if (response.statusCode == 404) {
39 + return "Not Found";
40 + } else {
41 + return "Error";
42 + }
43 + }
44 +
45 + Future<String> deleteHub(int index) async {
46 + String usertoken = await UserSecureStorage.getUserToken();
47 + http.Response response = await http.delete(
48 + Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub/' + index.toString()),
49 + headers: {"authorization": usertoken},
50 + );
51 + if (response.statusCode == 204) {
52 + return "Delete";
53 + } else {
54 + return "Error";
55 + }
56 + }
57 +
58 + Widget build(BuildContext context) {
59 + final Size size = MediaQuery.of(context).size;
60 + return Scaffold(
61 + appBar: AppBar(
62 + backgroundColor: Colors.white,
63 + leading: new Icon(Icons.medical_services_rounded,
64 + color: Colors.black, size: 45.0),
65 + title: Text(
66 + 'Smart Medicine Box',
67 + style: TextStyle(
68 + color: Colors.black,
69 + fontSize: 23,
70 + fontFamily: 'Noto',
71 + fontWeight: FontWeight.bold),
72 + ),
73 + ),
74 + body: FutureBuilder(
75 + future: getHubList(),
76 + builder: (BuildContext context, AsyncSnapshot snapshot) {
77 + if (snapshot.hasData == false) {
78 + return CircularProgressIndicator();
79 + } else if (snapshot.hasError) {
80 + return Padding(
81 + padding: const EdgeInsets.all(8.0),
82 + child: Text(
83 + 'Error: ${snapshot.error}',
84 + style: TextStyle(fontSize: 15),
85 + ),
86 + );
87 + } else {
88 + return Container(
89 + height: size.height,
90 + child: Column(
91 + mainAxisAlignment: MainAxisAlignment.center,
92 + children: <Widget>[
93 + Container(
94 + height: size.height * 0.1,
95 + width: size.width,
96 + child: Center(
97 + child: Text(
98 + '등록된 허브 리스트',
99 + textScaleFactor: 1.0,
100 + style: TextStyle(
101 + fontSize: 28,
102 + fontFamily: 'Noto',
103 + fontWeight: FontWeight.bold),
104 + ),
105 + ),
106 + decoration: BoxDecoration(border: Border.all()),
107 + ),
108 + SizedBox(height: 30),
109 + Expanded(
110 + child: ListView.separated(
111 + padding: const EdgeInsets.all(30),
112 + itemCount:
113 + _hublist.length == null ? 0 : _hublist.length,
114 + itemBuilder: (BuildContext context, int index) {
115 + return Container(
116 + padding: EdgeInsets.all(8.0),
117 + decoration: BoxDecoration(
118 + border: Border.all(),
119 + borderRadius:
120 + BorderRadius.all(Radius.circular(25.0)),
121 + ),
122 + child: ListTile(
123 + title: Text(
124 + 'HUB ID: ' + '${_hublist[index]}',
125 + style: TextStyle(
126 + color: Colors.black,
127 + fontSize: 20,
128 + fontFamily: 'Noto',
129 + fontWeight: FontWeight.bold),
130 + ),
131 + trailing: Icon(Icons.highlight_remove),
132 + onTap: () async {
133 + if (_hublist.length == 1) {
134 + showDialog(
135 + context: context,
136 + builder: (BuildContext context) {
137 + return AlertDialog(
138 + title: new Text('허브 삭제'),
139 + content: new Text(
140 + '등록된 허브가 하나이므로 해제가 불가능 합니다.'),
141 + actions: <Widget>[
142 + new FlatButton(
143 + child: new Text('Cloes'),
144 + onPressed: () {
145 + Navigator.of(context).pop();
146 + }),
147 + ],
148 + );
149 + },
150 + );
151 + } else {
152 + showDialog(
153 + context: context,
154 + builder: (BuildContext context) {
155 + return AlertDialog(
156 + title: new Text('허브 삭제'),
157 + content: new Text(
158 + _hublist[index].toString() +
159 + '을 삭제 하시겠습니까?'),
160 + actions: <Widget>[
161 + new FlatButton(
162 + child: new Text('삭제'),
163 + onPressed: () async {
164 + await deleteHub(_hublist[index]);
165 + setState(() {});
166 + Navigator.of(context).pop();
167 + },
168 + ),
169 + new FlatButton(
170 + child: new Text('취소'),
171 + onPressed: () {
172 + Navigator.of(context).pop();
173 + },
174 + )
175 + ],
176 + );
177 + },
178 + );
179 + }
180 + },
181 + ),
182 + );
183 + },
184 + separatorBuilder: (BuildContext contetx, int index) =>
185 + const Divider(),
186 + ),
187 + ),
188 + Container(
189 + padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
190 + width: size.width * 0.8,
191 + height: size.height * 0.13,
192 + margin: EdgeInsets.only(bottom: 0),
193 + child: FlatButton(
194 + height: size.height * 0.07,
195 + onPressed: () async {
196 + await Navigator.push(
197 + context,
198 + MaterialPageRoute(
199 + builder: (BuildContext context) =>
200 + RegisterHub(modify_hub: 1),
201 + ),
202 + );
203 + setState(() {});
204 + },
205 + child: Text(
206 + '허브 추가',
207 + textScaleFactor: 1.0,
208 + style: TextStyle(
209 + color: Colors.white,
210 + fontSize: 24,
211 + fontFamily: 'Noto',
212 + fontWeight: FontWeight.bold),
213 + ),
214 + color: Color(0xff0B1E33),
215 + shape: RoundedRectangleBorder(
216 + borderRadius: BorderRadius.circular(50)),
217 + ),
218 + ),
219 + ],
220 + ),
221 + );
222 + }
223 + }),
224 + );
225 + }
226 +}
1 +import 'package:flutter/material.dart';
2 +import 'package:flutter/services.dart';
3 +import 'package:Smart_Medicine_Box/src/screens/SettingPage.dart';
4 +
5 +class InformationModify extends StatefulWidget {
6 + @override
7 + _InformationModifyState createState() => _InformationModifyState();
8 +}
9 +
10 +class _InformationModifyState extends State<InformationModify> {
11 + final passwordController = TextEditingController();
12 + final passwordValidController = TextEditingController();
13 + final medicineNameController = TextEditingController();
14 + final medicineFactureController = TextEditingController();
15 + bool _validate = false;
16 + int userRole = 0;
17 +
18 + // Initially password is obscure
19 + bool passwordVisible = false;
20 + bool passwordValidationVisible = true;
21 +
22 + Widget build(BuildContext context) {
23 + final Size size = MediaQuery.of(context).size;
24 + return Scaffold(
25 + appBar: AppBar(
26 + iconTheme: IconThemeData(color: Colors.black),
27 + backgroundColor: Colors.white,
28 + title: Text(
29 + 'Smart Medicine Box',
30 + style: TextStyle(
31 + color: Colors.black,
32 + fontSize: 20,
33 + fontFamily: 'Noto',
34 + fontWeight: FontWeight.bold),
35 + ),
36 + actions: [
37 + IconButton(
38 + icon: Icon(
39 + Icons.settings,
40 + color: Colors.black,
41 + ),
42 + onPressed: () {
43 + Navigator.push(
44 + context,
45 + MaterialPageRoute(
46 + builder: (BuildContext context) => SettingPage(),
47 + ));
48 + },
49 + )
50 + ],
51 + ),
52 + body: ListView(
53 + children: <Widget>[
54 + Container(
55 + height: size.height * 0.9,
56 + margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
57 + padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
58 + child: Column(
59 + children: <Widget>[
60 + Container(
61 + padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
62 + height: size.height * 0.08,
63 + width: size.width,
64 + child: Center(
65 + child: Text(
66 + '회원 정보 수정',
67 + textAlign: TextAlign.center,
68 + textScaleFactor: 1.0,
69 + style: TextStyle(
70 + color: Colors.black,
71 + fontSize: 32,
72 + fontFamily: 'NotoSansKR',
73 + fontWeight: FontWeight.w700),
74 + ),
75 + ),
76 + ),
77 + MediaQuery(
78 + data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
79 + child: Container(
80 + height: size.height * 0.6,
81 + child: Padding(
82 + padding: const EdgeInsets.fromLTRB(20, 5, 20, 20),
83 + child: new Column(
84 + children: <Widget>[
85 + SizedBox(height: 15),
86 + Container(
87 + height: size.height * 0.091,
88 + padding: const EdgeInsets.fromLTRB(5, 10, 5, 5),
89 + child: Container(
90 + width: size.width * 0.85,
91 + padding: const EdgeInsets.fromLTRB(5, 16, 5, 3),
92 + decoration: BoxDecoration(
93 + color: Color(0xffBDBDBD),
94 + border: Border.all(),
95 + borderRadius:
96 + BorderRadius.all(Radius.circular(5))),
97 + child: Text(
98 + 'test@naver.com',
99 + textScaleFactor: 1.0,
100 + style: TextStyle(
101 + color: Colors.black,
102 + fontSize: 18,
103 + fontFamily: 'NotoSansKR',
104 + ),
105 + ),
106 + ),
107 + ),
108 + SizedBox(height: 15),
109 + Container(
110 + height: size.height * 0.13,
111 + padding: const EdgeInsets.fromLTRB(5, 10, 5, 5),
112 + child: TextFormField(
113 + keyboardType: TextInputType.text,
114 + controller: passwordController,
115 + obscureText:
116 + !passwordVisible, //This will obscure text dynamically
117 + decoration: InputDecoration(
118 + border: OutlineInputBorder(
119 + borderSide:
120 + BorderSide(color: Colors.black)),
121 + labelText: '비밀번호',
122 + helperText: '비밀번호를 입력해주세요',
123 + // Here is key idea
124 + suffixIcon: IconButton(
125 + icon: Icon(
126 + // Based on passwordVisible state choose the icon
127 + passwordVisible
128 + ? Icons.visibility
129 + : Icons.visibility_off,
130 + color: Theme.of(context).primaryColorDark,
131 + ),
132 + onPressed: () {
133 + // Update the state i.e. toogle the state of passwordVisible variable
134 + setState(() {
135 + passwordVisible = !passwordVisible;
136 + });
137 + },
138 + ),
139 + ),
140 + ),
141 + ),
142 + Container(
143 + height: size.height * 0.13,
144 + padding: const EdgeInsets.fromLTRB(5, 10, 5, 5),
145 + child: TextFormField(
146 + keyboardType: TextInputType.text,
147 + controller: medicineNameController,
148 + decoration: InputDecoration(
149 + border: OutlineInputBorder(),
150 + labelText: '약 이름',
151 + helperText: '약의 이름을 읿력하세요',
152 + ),
153 + ),
154 + ),
155 + Container(
156 + height: size.height * 0.13,
157 + padding: const EdgeInsets.fromLTRB(5, 10, 5, 5),
158 + child: TextFormField(
159 + keyboardType: TextInputType.text,
160 + controller: medicineFactureController,
161 + decoration: InputDecoration(
162 + border: OutlineInputBorder(),
163 + labelText: '약 제조사 이름',
164 + helperText: '약 제조사의 이름을 읿력하세요',
165 + ),
166 + ),
167 + ),
168 + ],
169 + ),
170 + ),
171 + ),
172 + ),
173 + Container(
174 + height: 100,
175 + width: size.width * 0.7,
176 + padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
177 + child: RaisedButton(
178 + onPressed: () async {},
179 + shape: RoundedRectangleBorder(
180 + borderRadius: new BorderRadius.circular(20.0),
181 + side: BorderSide(color: Colors.blue)),
182 + color: Color(0xff1674f6),
183 + child: Text(
184 + '회원 정보 수정',
185 + textScaleFactor: 1.0,
186 + style: TextStyle(
187 + fontSize: 16,
188 + color: Colors.white,
189 + fontWeight: FontWeight.bold),
190 + ),
191 + ),
192 + )
193 + ],
194 + ),
195 + ),
196 + ],
197 + ),
198 + );
199 + }
200 +}
1 +import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
2 +
3 +class CustomPicker extends CommonPickerModel {
4 + var indexs;
5 +
6 + String digits(int value, int length) {
7 + return '$value'.padLeft(length, "0");
8 + }
9 +
10 + CustomPicker({DateTime currentTime, LocaleType locale})
11 + : super(locale: LocaleType.ko) {
12 + this.currentTime = currentTime ?? DateTime.now();
13 + var _dayPeriod = 0;
14 + this.setLeftIndex(this.currentTime.hour);
15 + this.setMiddleIndex(this.currentTime.minute);
16 + this.setRightIndex(_dayPeriod);
17 + _fillRightList();
18 + }
19 +
20 + @override
21 + String leftStringAtIndex(int index) {
22 + if (index >= 1 && index < 13) {
23 + return this.digits(index, 2);
24 + } else {
25 + return null;
26 + }
27 + }
28 +
29 + @override
30 + String middleStringAtIndex(int index) {
31 + if (index >= 0 && index < 60) {
32 + return this.digits(index, 2);
33 + } else {
34 + return null;
35 + }
36 + }
37 +
38 + @override
39 + String rightStringAtIndex(int index) {
40 + if (index == 0) {
41 + return 'AM';
42 + } else if (index == 1) {
43 + return 'PM';
44 + }
45 + return null;
46 + }
47 +
48 + void _fillRightList() {
49 + this.rightList = List.generate(2, (int index) {
50 + return '$index';
51 + });
52 + }
53 +
54 + @override
55 + void setRightIndex(int index) {
56 + super.setRightIndex(index);
57 + indexs = index;
58 + _fillRightList();
59 + }
60 +
61 + @override
62 + String leftDivider() {
63 + return ":";
64 + }
65 +
66 + @override
67 + String rightDivider() {
68 + return " ";
69 + }
70 +
71 + @override
72 + List<int> layoutProportions() {
73 + return [1, 1, 1];
74 + }
75 +
76 + @override
77 + DateTime finalTime() {
78 + var leftindex;
79 +
80 + if (indexs == 1) {
81 + if (this.currentLeftIndex() == 12) {
82 + leftindex = 12;
83 + } else {
84 + leftindex = this.currentLeftIndex() + 12;
85 + }
86 + } else if (indexs == 0) {
87 + if (this.currentLeftIndex() == 12) {
88 + leftindex = 0;
89 + } else {
90 + leftindex = this.currentLeftIndex();
91 + }
92 + }
93 +
94 + return currentTime.isUtc
95 + ? DateTime.utc(currentTime.year, currentTime.month, currentTime.day,
96 + leftindex, this.currentMiddleIndex(), this.currentRightIndex())
97 + : DateTime(currentTime.year, currentTime.month, currentTime.day,
98 + leftindex, this.currentMiddleIndex(), this.currentRightIndex());
99 + }
100 +}
1 +class Bottle {
2 + final int bottleId;
3 + final String temperature;
4 + final String humidity;
5 + final String balance;
6 + final DateTime recentOpen;
7 + final int medicineId;
8 + final int hubId;
9 + final int dosage;
10 +
11 + Bottle(
12 + {this.bottleId,
13 + this.temperature,
14 + this.humidity,
15 + this.balance,
16 + this.recentOpen,
17 + this.medicineId,
18 + this.hubId,
19 + this.dosage});
20 +
21 + factory Bottle.fromJson(Map<String, dynamic> parsedJson) {
22 + return Bottle(
23 + bottleId: parsedJson['bottleId'],
24 + temperature: parsedJson['temperature'].toString(),
25 + humidity: parsedJson['humidity'].toString(),
26 + balance: parsedJson['balance'].toString(),
27 + recentOpen: DateTime.parse(parsedJson['recentOpen']).toLocal(),
28 + medicineId: parsedJson['medicineId'],
29 + hubId: parsedJson['hubId'],
30 + dosage: parsedJson['dosage'],
31 + );
32 + }
33 +
34 + Map<String, dynamic> toJson() => {
35 + "bottleId": bottleId,
36 + "temperature": temperature,
37 + "humidity:": humidity,
38 + "balance": balance,
39 + "recentOpen": recentOpen,
40 + "medicineId": medicineId,
41 + "hubId": hubId,
42 + "dosage": dosage,
43 + };
44 +}
1 +import 'Medicine.dart';
2 +
3 +class Data {
4 + final int totalItem;
5 + final List<Medicine> result;
6 +
7 + Data({this.totalItem, this.result});
8 +
9 + factory Data.fromJson(Map<String, dynamic> parsedJson) {
10 + var list = parsedJson['result'] as List;
11 + List<Medicine> resultList = list.map((i) => Medicine.fromJson(i)).toList();
12 +
13 + return Data(
14 + totalItem: parsedJson['totalItem'],
15 + result: resultList,
16 + );
17 + }
18 + Map<String, dynamic> toJson() => {
19 + "totalItem": totalItem,
20 + "result": result,
21 + };
22 +}
1 +class Medicine {
2 + final int medicineId;
3 + final String antiEffect;
4 + final String company;
5 + final String dosage;
6 + final String name;
7 + final String target;
8 + final String warn;
9 +
10 + Medicine(
11 + {this.medicineId,
12 + this.antiEffect,
13 + this.company,
14 + this.dosage,
15 + this.name,
16 + this.target,
17 + this.warn});
18 +
19 + factory Medicine.fromJson(Map<String, dynamic> parsedJson) {
20 + return Medicine(
21 + medicineId: parsedJson['medicineId'],
22 + antiEffect: parsedJson['antiEffect'],
23 + company: parsedJson['company'],
24 + dosage: parsedJson['dosage'],
25 + name: parsedJson['name'],
26 + target: parsedJson['target'],
27 + warn: parsedJson['warn'],
28 + );
29 + }
30 +
31 + Map<String, dynamic> toJson() => {
32 + "medicineId": medicineId,
33 + "antiEffect": antiEffect,
34 + "company": company,
35 + "dosage": dosage,
36 + "name": name,
37 + "target": target,
38 + "warn": warn,
39 + };
40 +}
1 +class User {
2 + final String userId;
3 + final String token;
4 +
5 + User({this.userId, this.token});
6 +
7 + factory User.fromJson(Map<String, dynamic> parsedJson) {
8 + return User(
9 + userId: parsedJson['userId'],
10 + token: parsedJson['token'],
11 + );
12 + }
13 + Map<String, dynamic> toJson() => {
14 + "userId": userId,
15 + "token": token,
16 + };
17 +}
1 +import 'package:flutter/material.dart';
2 +
3 + const Color bgColor = Color(0xffF4F7FA);
4 +// const Color primaryColor = Colors.green;
5 + const Color primaryColor = Color(0xff44c662);
6 + const Color white = Colors.white;
7 + const Color darkText = Colors.black54;
8 + const Color highlightColor = Colors.green;
1 +import 'package:flutter/material.dart';
2 +import './colors.dart';
3 +import './styles.dart';
4 +
5 +Container fryoTextInput(String hintText,
6 + {onTap, onChanged, onEditingComplete, onSubmitted}) {
7 + return Container(
8 + margin: EdgeInsets.only(top: 13),
9 + child: TextField(
10 + onTap: onTap,
11 + onChanged: onChanged,
12 + onEditingComplete: onEditingComplete,
13 + onSubmitted: onSubmitted,
14 + cursorColor: primaryColor,
15 + style: inputFieldTextStyle,
16 + decoration: InputDecoration(
17 + hintText: hintText,
18 + hintStyle: inputFieldHintTextStyle,
19 + focusedBorder: inputFieldFocusedBorderStyle,
20 + contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
21 + border: inputFieldDefaultBorderStyle),
22 + ),
23 + );
24 +}
25 +
26 +Container fryoEmailInput(String hintText,
27 + {onTap, onChanged, onEditingComplete, onSubmitted}) {
28 + return Container(
29 + margin: EdgeInsets.only(top: 13),
30 + child: TextField(
31 + onTap: onTap,
32 + onChanged: onChanged,
33 + onEditingComplete: onEditingComplete,
34 + onSubmitted: onSubmitted,
35 + keyboardType: TextInputType.emailAddress,
36 + cursorColor: primaryColor,
37 + style: inputFieldTextStyle,
38 + decoration: InputDecoration(
39 + hintText: hintText,
40 + hintStyle: inputFieldHintTextStyle,
41 + focusedBorder: inputFieldFocusedBorderStyle,
42 + contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
43 + border: inputFieldDefaultBorderStyle),
44 + ),
45 + );
46 +}
47 +
48 +
49 +Container fryoPasswordInput(String hintText,
50 + {onTap, onChanged, onEditingComplete, onSubmitted}) {
51 + return Container(
52 + margin: EdgeInsets.only(top: 13),
53 + child: TextField(
54 + onTap: onTap,
55 + onChanged: onChanged,
56 + onEditingComplete: onEditingComplete,
57 + onSubmitted: onSubmitted,
58 + obscureText: true,
59 + cursorColor: primaryColor,
60 + style: inputFieldHintPaswordTextStyle,
61 + decoration: InputDecoration(
62 + hintText: hintText,
63 + hintStyle: inputFieldHintPaswordTextStyle,
64 + focusedBorder: inputFieldFocusedBorderStyle,
65 + contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
66 + border: inputFieldDefaultBorderStyle),
67 + ),
68 + );
69 +}
1 +import 'package:flutter/material.dart';
2 +import './colors.dart';
3 +
4 +/////////////////////////////////
5 +/// TEXT STYLES
6 +////////////////////////////////
7 +
8 +const logoStyle = TextStyle(
9 + fontFamily: 'Pacifico',
10 + fontSize: 30,
11 + color: Colors.black54,
12 + letterSpacing: 2);
13 +
14 +const logoWhiteStyle = TextStyle(
15 + fontFamily: 'Pacifico',
16 + fontSize: 21,
17 + letterSpacing: 2,
18 + color: Colors.white);
19 +const whiteText = TextStyle(color: Colors.white, fontFamily: 'Poppins');
20 +const disabledText = TextStyle(color: Colors.grey, fontFamily: 'Poppins');
21 +const contrastText = TextStyle(color: primaryColor, fontFamily: 'Poppins');
22 +const contrastTextBold = TextStyle(
23 + color: primaryColor, fontFamily: 'Poppins', fontWeight: FontWeight.w600);
24 +
25 +const h3 = TextStyle(
26 + color: Colors.black,
27 + fontSize: 24,
28 + fontWeight: FontWeight.w800,
29 + fontFamily: 'Poppins');
30 +
31 +const h4 = TextStyle(
32 + color: Colors.black,
33 + fontSize: 18,
34 + fontWeight: FontWeight.w700,
35 + fontFamily: 'Poppins');
36 +
37 +const h5 = TextStyle(
38 + color: Colors.black,
39 + fontSize: 18,
40 + fontWeight: FontWeight.w500,
41 + fontFamily: 'Poppins');
42 +
43 + const h6 = TextStyle(
44 + color: Colors.black,
45 + fontSize: 16,
46 + fontWeight: FontWeight.w500,
47 + fontFamily: 'Poppins');
48 +
49 +
50 +const priceText = TextStyle(
51 + color: Colors.black,
52 + fontSize: 19,
53 + fontWeight: FontWeight.w800,
54 + fontFamily: 'Poppins');
55 +
56 +const foodNameText = TextStyle(
57 + color: Colors.black,
58 + fontSize: 17,
59 + fontWeight: FontWeight.w600,
60 + fontFamily: 'Poppins');
61 +
62 +const tabLinkStyle =
63 + TextStyle(fontWeight: FontWeight.w500);
64 +
65 +const taglineText = TextStyle(color: Colors.grey, fontFamily: 'Poppins');
66 +const categoryText = TextStyle(
67 + color: Color(0xff444444),
68 + fontWeight: FontWeight.w700,
69 + fontFamily: 'Poppins');
70 +
71 +const inputFieldTextStyle =
72 + TextStyle(fontFamily: 'Poppins', fontWeight: FontWeight.w500);
73 +
74 +const inputFieldHintTextStyle =
75 + TextStyle(fontFamily: 'Poppins', color: Color(0xff444444));
76 +
77 +const inputFieldPasswordTextStyle = TextStyle(
78 + fontFamily: 'Poppins', fontWeight: FontWeight.w500, letterSpacing: 3);
79 +
80 +const inputFieldHintPaswordTextStyle = TextStyle(
81 + fontFamily: 'Poppins', color: Color(0xff444444), letterSpacing: 2);
82 +
83 +///////////////////////////////////
84 +/// BOX DECORATION STYLES
85 +//////////////////////////////////
86 +
87 +const authPlateDecoration = BoxDecoration(
88 + color: white,
89 + boxShadow: [
90 + BoxShadow(
91 + color: Color.fromRGBO(0, 0, 0, .1),
92 + blurRadius: 10,
93 + spreadRadius: 5,
94 + offset: Offset(0, 1))
95 + ],
96 + borderRadius: BorderRadiusDirectional.only(
97 + bottomEnd: Radius.circular(20), bottomStart: Radius.circular(20)));
98 +
99 +/////////////////////////////////////
100 +/// INPUT FIELD DECORATION STYLES
101 +////////////////////////////////////
102 +
103 +const inputFieldFocusedBorderStyle = OutlineInputBorder(
104 + borderRadius: BorderRadius.all(Radius.circular(6)),
105 + borderSide: BorderSide(
106 + color: primaryColor,
107 + ));
108 +
109 +const inputFieldDefaultBorderStyle = OutlineInputBorder(
110 + gapPadding: 0, borderRadius: BorderRadius.all(Radius.circular(6)));
1 +import 'package:flutter_secure_storage/flutter_secure_storage.dart';
2 +
3 +class UserSecureStorage {
4 + static final _storage = FlutterSecureStorage();
5 +
6 + static const _keyToken = 'usertoken';
7 +
8 + static const _keyUserId = 'userid';
9 +
10 + static const _keyBottleId = 'bottleid';
11 +
12 + static const _keyMedicineId = 'medicineid';
13 +
14 + static const _keyhubId = 'hubid';
15 +
16 + static Future setUserId(String userid) async =>
17 + await _storage.write(key: _keyUserId, value: userid);
18 +
19 + static Future<String> getUserID() async =>
20 + await _storage.read(key: _keyUserId);
21 +
22 + static Future setUserToken(String userToken) async =>
23 + await _storage.write(key: _keyToken, value: userToken);
24 +
25 + static Future<String> getUserToken() async =>
26 + await _storage.read(key: _keyToken);
27 +
28 + static Future setBottleId(String bottleid) async =>
29 + await _storage.write(key: _keyBottleId, value: bottleid);
30 +
31 + static Future<String> getBottleId() async =>
32 + await _storage.read(key: _keyBottleId);
33 +
34 + static Future setMedicineId(String medicineid) async =>
35 + await _storage.write(key: _keyMedicineId, value: medicineid);
36 +
37 + static Future<String> getMedicineId() async =>
38 + await _storage.read(key: _keyMedicineId);
39 +
40 + static Future setHubId(String hubid) async =>
41 + await _storage.write(key: _keyhubId, value: hubid);
42 +
43 + static Future<String> getHubId() async => await _storage.read(key: _keyhubId);
44 +}
1 +# Generated by pub
2 +# See https://dart.dev/tools/pub/glossary#lockfile
3 +packages:
4 + async:
5 + dependency: transitive
6 + description:
7 + name: async
8 + url: "https://pub.dartlang.org"
9 + source: hosted
10 + version: "2.5.0-nullsafety.1"
11 + boolean_selector:
12 + dependency: transitive
13 + description:
14 + name: boolean_selector
15 + url: "https://pub.dartlang.org"
16 + source: hosted
17 + version: "2.1.0-nullsafety.1"
18 + characters:
19 + dependency: transitive
20 + description:
21 + name: characters
22 + url: "https://pub.dartlang.org"
23 + source: hosted
24 + version: "1.1.0-nullsafety.3"
25 + charcode:
26 + dependency: transitive
27 + description:
28 + name: charcode
29 + url: "https://pub.dartlang.org"
30 + source: hosted
31 + version: "1.2.0-nullsafety.1"
32 + clock:
33 + dependency: transitive
34 + description:
35 + name: clock
36 + url: "https://pub.dartlang.org"
37 + source: hosted
38 + version: "1.1.0-nullsafety.1"
39 + collection:
40 + dependency: transitive
41 + description:
42 + name: collection
43 + url: "https://pub.dartlang.org"
44 + source: hosted
45 + version: "1.15.0-nullsafety.3"
46 + convert:
47 + dependency: transitive
48 + description:
49 + name: convert
50 + url: "https://pub.dartlang.org"
51 + source: hosted
52 + version: "2.1.1"
53 + cupertino_icons:
54 + dependency: "direct main"
55 + description:
56 + name: cupertino_icons
57 + url: "https://pub.dartlang.org"
58 + source: hosted
59 + version: "0.1.3"
60 + fake_async:
61 + dependency: transitive
62 + description:
63 + name: fake_async
64 + url: "https://pub.dartlang.org"
65 + source: hosted
66 + version: "1.2.0-nullsafety.1"
67 + ffi:
68 + dependency: transitive
69 + description:
70 + name: ffi
71 + url: "https://pub.dartlang.org"
72 + source: hosted
73 + version: "0.1.3"
74 + file:
75 + dependency: transitive
76 + description:
77 + name: file
78 + url: "https://pub.dartlang.org"
79 + source: hosted
80 + version: "5.2.1"
81 + fixnum:
82 + dependency: transitive
83 + description:
84 + name: fixnum
85 + url: "https://pub.dartlang.org"
86 + source: hosted
87 + version: "0.10.11"
88 + flutter:
89 + dependency: "direct main"
90 + description: flutter
91 + source: sdk
92 + version: "0.0.0"
93 + flutter_blue:
94 + dependency: "direct main"
95 + description:
96 + name: flutter_blue
97 + url: "https://pub.dartlang.org"
98 + source: hosted
99 + version: "0.7.2"
100 + flutter_datetime_picker:
101 + dependency: "direct main"
102 + description:
103 + name: flutter_datetime_picker
104 + url: "https://pub.dartlang.org"
105 + source: hosted
106 + version: "1.5.0"
107 + flutter_dotenv:
108 + dependency: "direct main"
109 + description:
110 + name: flutter_dotenv
111 + url: "https://pub.dartlang.org"
112 + source: hosted
113 + version: "2.1.0"
114 + flutter_local_notifications:
115 + dependency: "direct main"
116 + description:
117 + name: flutter_local_notifications
118 + url: "https://pub.dartlang.org"
119 + source: hosted
120 + version: "1.5.0+1"
121 + flutter_local_notifications_platform_interface:
122 + dependency: transitive
123 + description:
124 + name: flutter_local_notifications_platform_interface
125 + url: "https://pub.dartlang.org"
126 + source: hosted
127 + version: "1.0.1"
128 + flutter_screenutil:
129 + dependency: "direct main"
130 + description:
131 + name: flutter_screenutil
132 + url: "https://pub.dartlang.org"
133 + source: hosted
134 + version: "0.7.0"
135 + flutter_secure_storage:
136 + dependency: "direct main"
137 + description:
138 + name: flutter_secure_storage
139 + url: "https://pub.dartlang.org"
140 + source: hosted
141 + version: "3.3.5"
142 + flutter_test:
143 + dependency: "direct dev"
144 + description: flutter
145 + source: sdk
146 + version: "0.0.0"
147 + flutter_web_plugins:
148 + dependency: transitive
149 + description: flutter
150 + source: sdk
151 + version: "0.0.0"
152 + http:
153 + dependency: "direct main"
154 + description:
155 + name: http
156 + url: "https://pub.dartlang.org"
157 + source: hosted
158 + version: "0.12.2"
159 + http_parser:
160 + dependency: transitive
161 + description:
162 + name: http_parser
163 + url: "https://pub.dartlang.org"
164 + source: hosted
165 + version: "3.1.4"
166 + infinite_listview:
167 + dependency: transitive
168 + description:
169 + name: infinite_listview
170 + url: "https://pub.dartlang.org"
171 + source: hosted
172 + version: "1.0.1+1"
173 + intl:
174 + dependency: "direct main"
175 + description:
176 + name: intl
177 + url: "https://pub.dartlang.org"
178 + source: hosted
179 + version: "0.16.1"
180 + logging:
181 + dependency: transitive
182 + description:
183 + name: logging
184 + url: "https://pub.dartlang.org"
185 + source: hosted
186 + version: "0.11.4"
187 + mailer:
188 + dependency: "direct main"
189 + description:
190 + name: mailer
191 + url: "https://pub.dartlang.org"
192 + source: hosted
193 + version: "3.3.0"
194 + matcher:
195 + dependency: transitive
196 + description:
197 + name: matcher
198 + url: "https://pub.dartlang.org"
199 + source: hosted
200 + version: "0.12.10-nullsafety.1"
201 + meta:
202 + dependency: transitive
203 + description:
204 + name: meta
205 + url: "https://pub.dartlang.org"
206 + source: hosted
207 + version: "1.3.0-nullsafety.3"
208 + mime:
209 + dependency: transitive
210 + description:
211 + name: mime
212 + url: "https://pub.dartlang.org"
213 + source: hosted
214 + version: "0.9.7"
215 + numberpicker:
216 + dependency: "direct main"
217 + description:
218 + name: numberpicker
219 + url: "https://pub.dartlang.org"
220 + source: hosted
221 + version: "1.3.0"
222 + page_transition:
223 + dependency: "direct main"
224 + description:
225 + name: page_transition
226 + url: "https://pub.dartlang.org"
227 + source: hosted
228 + version: "1.1.7+6"
229 + path:
230 + dependency: transitive
231 + description:
232 + name: path
233 + url: "https://pub.dartlang.org"
234 + source: hosted
235 + version: "1.8.0-nullsafety.1"
236 + path_provider:
237 + dependency: "direct main"
238 + description:
239 + name: path_provider
240 + url: "https://pub.dartlang.org"
241 + source: hosted
242 + version: "1.6.28"
243 + path_provider_linux:
244 + dependency: transitive
245 + description:
246 + name: path_provider_linux
247 + url: "https://pub.dartlang.org"
248 + source: hosted
249 + version: "0.0.1+2"
250 + path_provider_macos:
251 + dependency: transitive
252 + description:
253 + name: path_provider_macos
254 + url: "https://pub.dartlang.org"
255 + source: hosted
256 + version: "0.0.4+8"
257 + path_provider_platform_interface:
258 + dependency: transitive
259 + description:
260 + name: path_provider_platform_interface
261 + url: "https://pub.dartlang.org"
262 + source: hosted
263 + version: "1.0.4"
264 + path_provider_windows:
265 + dependency: transitive
266 + description:
267 + name: path_provider_windows
268 + url: "https://pub.dartlang.org"
269 + source: hosted
270 + version: "0.0.4+3"
271 + pedantic:
272 + dependency: transitive
273 + description:
274 + name: pedantic
275 + url: "https://pub.dartlang.org"
276 + source: hosted
277 + version: "1.9.0"
278 + platform:
279 + dependency: transitive
280 + description:
281 + name: platform
282 + url: "https://pub.dartlang.org"
283 + source: hosted
284 + version: "2.2.1"
285 + plugin_platform_interface:
286 + dependency: transitive
287 + description:
288 + name: plugin_platform_interface
289 + url: "https://pub.dartlang.org"
290 + source: hosted
291 + version: "1.0.3"
292 + process:
293 + dependency: transitive
294 + description:
295 + name: process
296 + url: "https://pub.dartlang.org"
297 + source: hosted
298 + version: "3.0.13"
299 + protobuf:
300 + dependency: transitive
301 + description:
302 + name: protobuf
303 + url: "https://pub.dartlang.org"
304 + source: hosted
305 + version: "1.1.3"
306 + rxdart:
307 + dependency: "direct main"
308 + description:
309 + name: rxdart
310 + url: "https://pub.dartlang.org"
311 + source: hosted
312 + version: "0.24.1"
313 + shared_preferences:
314 + dependency: "direct main"
315 + description:
316 + name: shared_preferences
317 + url: "https://pub.dartlang.org"
318 + source: hosted
319 + version: "0.5.12+4"
320 + shared_preferences_linux:
321 + dependency: transitive
322 + description:
323 + name: shared_preferences_linux
324 + url: "https://pub.dartlang.org"
325 + source: hosted
326 + version: "0.0.2+4"
327 + shared_preferences_macos:
328 + dependency: transitive
329 + description:
330 + name: shared_preferences_macos
331 + url: "https://pub.dartlang.org"
332 + source: hosted
333 + version: "0.0.1+11"
334 + shared_preferences_platform_interface:
335 + dependency: transitive
336 + description:
337 + name: shared_preferences_platform_interface
338 + url: "https://pub.dartlang.org"
339 + source: hosted
340 + version: "1.0.4"
341 + shared_preferences_web:
342 + dependency: transitive
343 + description:
344 + name: shared_preferences_web
345 + url: "https://pub.dartlang.org"
346 + source: hosted
347 + version: "0.1.2+7"
348 + shared_preferences_windows:
349 + dependency: transitive
350 + description:
351 + name: shared_preferences_windows
352 + url: "https://pub.dartlang.org"
353 + source: hosted
354 + version: "0.0.2+3"
355 + sky_engine:
356 + dependency: transitive
357 + description: flutter
358 + source: sdk
359 + version: "0.0.99"
360 + source_span:
361 + dependency: transitive
362 + description:
363 + name: source_span
364 + url: "https://pub.dartlang.org"
365 + source: hosted
366 + version: "1.8.0-nullsafety.2"
367 + sqflite:
368 + dependency: "direct main"
369 + description:
370 + name: sqflite
371 + url: "https://pub.dartlang.org"
372 + source: hosted
373 + version: "1.3.1+2"
374 + sqflite_common:
375 + dependency: transitive
376 + description:
377 + name: sqflite_common
378 + url: "https://pub.dartlang.org"
379 + source: hosted
380 + version: "1.0.3+3"
381 + stack_trace:
382 + dependency: transitive
383 + description:
384 + name: stack_trace
385 + url: "https://pub.dartlang.org"
386 + source: hosted
387 + version: "1.10.0-nullsafety.1"
388 + stream_channel:
389 + dependency: transitive
390 + description:
391 + name: stream_channel
392 + url: "https://pub.dartlang.org"
393 + source: hosted
394 + version: "2.1.0-nullsafety.1"
395 + string_scanner:
396 + dependency: transitive
397 + description:
398 + name: string_scanner
399 + url: "https://pub.dartlang.org"
400 + source: hosted
401 + version: "1.1.0-nullsafety.1"
402 + synchronized:
403 + dependency: transitive
404 + description:
405 + name: synchronized
406 + url: "https://pub.dartlang.org"
407 + source: hosted
408 + version: "2.2.0+2"
409 + term_glyph:
410 + dependency: transitive
411 + description:
412 + name: term_glyph
413 + url: "https://pub.dartlang.org"
414 + source: hosted
415 + version: "1.2.0-nullsafety.1"
416 + test_api:
417 + dependency: transitive
418 + description:
419 + name: test_api
420 + url: "https://pub.dartlang.org"
421 + source: hosted
422 + version: "0.2.19-nullsafety.2"
423 + timezone:
424 + dependency: "direct main"
425 + description:
426 + name: timezone
427 + url: "https://pub.dartlang.org"
428 + source: hosted
429 + version: "0.6.1"
430 + typed_data:
431 + dependency: transitive
432 + description:
433 + name: typed_data
434 + url: "https://pub.dartlang.org"
435 + source: hosted
436 + version: "1.3.0-nullsafety.3"
437 + vector_math:
438 + dependency: transitive
439 + description:
440 + name: vector_math
441 + url: "https://pub.dartlang.org"
442 + source: hosted
443 + version: "2.1.0-nullsafety.3"
444 + win32:
445 + dependency: transitive
446 + description:
447 + name: win32
448 + url: "https://pub.dartlang.org"
449 + source: hosted
450 + version: "1.7.4+1"
451 + xdg_directories:
452 + dependency: transitive
453 + description:
454 + name: xdg_directories
455 + url: "https://pub.dartlang.org"
456 + source: hosted
457 + version: "0.1.0"
458 +sdks:
459 + dart: ">=2.10.0-110 <2.11.0"
460 + flutter: ">=1.20.0 <2.0.0"
1 +name: Smart_Medicine_Box
2 +description: A new Flutter project.
3 +
4 +# The following line prevents the package from being accidentally published to
5 +# pub.dev using `pub publish`. This is preferred for private packages.
6 +publish_to: 'none' # Remove this line if you wish to publish to pub.dev
7 +
8 +# The following defines the version and build number for your application.
9 +# A version number is three numbers separated by dots, like 1.2.43
10 +# followed by an optional build number separated by a +.
11 +# Both the version and the builder number may be overridden in flutter
12 +# build by specifying --build-name and --build-number, respectively.
13 +# In Android, build-name is used as versionName while build-number used as versionCode.
14 +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
15 +# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
16 +# Read more about iOS versioning at
17 +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
18 +version: 1.0.0+1
19 +
20 +environment:
21 + sdk: ">=2.7.0 <3.0.0"
22 +
23 +dependencies:
24 + flutter:
25 + sdk: flutter
26 +
27 + flutter_screenutil: ^0.7.0
28 + page_transition: '^1.1.5'
29 + mailer: '^3.0.4'
30 + flutter_local_notifications: ^1.4.4+5
31 + rxdart: ^0.24.0
32 + flutter_datetime_picker: ^1.3.4
33 + timezone: ^0.6.0
34 + intl : ^0.16.1
35 + shared_preferences: ^0.5.12+2
36 + flutter_blue: ^0.7.2
37 + cupertino_icons: ^0.1.3
38 + http: ^0.12.0+4
39 + flutter_dotenv: ^2.1.0
40 + numberpicker: ^1.3.0
41 + flutter_secure_storage: ^3.3.5
42 + sqflite: ^1.1.6
43 + path_provider: ^1.2.0
44 +
45 +dev_dependencies:
46 + flutter_test:
47 + sdk: flutter
48 +
49 +flutter:
50 +
51 +
52 + uses-material-design: true
53 +
54 + assets:
55 + - .env
56 + - images/
57 + - images/main_logo.png
58 + - images/setting.png
59 +
60 +fonts:
61 + # - family: Raleway
62 + # fonts:
63 + # - asset: fonts/Raleway-Regular.ttf
64 + # - asset: fonts/Raleway-Italic.ttf
65 + # style: italic
66 +- family: NotoSansKR
67 + fonts:
68 + - asset: assets/fonts/NotoSansKR-Regular.otf
69 + - asset: assets/fonts/NotoSansKR-Bold.otf
70 + weight: 500
71 + - asset: assets/fonts/NotoSansKR-Black.otf
72 + weight: 700
...\ No newline at end of file ...\ No newline at end of file
1 +// This is a basic Flutter widget test.
2 +//
3 +// To perform an interaction with a widget in your test, use the WidgetTester
4 +// utility that Flutter provides. For example, you can send tap and scroll
5 +// gestures. You can also use WidgetTester to find child widgets in the widget
6 +// tree, read text, and verify that the values of widget properties are correct.
7 +
8 +import 'package:flutter/material.dart';
9 +import 'package:flutter_test/flutter_test.dart';
10 +
11 +import 'package:Smart_Medicine_Box/main.dart';
12 +
13 +void main() {
14 + testWidgets('Counter increments smoke test', (WidgetTester tester) async {
15 + // Build our app and trigger a frame.
16 + await tester.pumpWidget(MyApp());
17 +
18 + // Verify that our counter starts at 0.
19 + expect(find.text('0'), findsOneWidget);
20 + expect(find.text('1'), findsNothing);
21 +
22 + // Tap the '+' icon and trigger a frame.
23 + await tester.tap(find.byIcon(Icons.add));
24 + await tester.pump();
25 +
26 + // Verify that our counter has incremented.
27 + expect(find.text('0'), findsNothing);
28 + expect(find.text('1'), findsOneWidget);
29 + });
30 +}
1 +# 스마트 약병 IoT 하드웨어 및 연결단 개발
2 +
3 +## 지도교수
4 ++ 유인태 교수님
5 +
6 +## 개발담당자
7 ++ 2015100552 컴퓨터공학과 윤형선
8 +
9 +## 일정
10 ++ 2021.05.03: Init(개인 아두이노 코드 git에서 이전)
11 ++ 2021.05.11: Arduino 개발 중단, RaspberryPi Pico로 플랫폼 이전, C++ -> MicroPython
12 ++ 2021.05.12: RaspberryPi Pico v0.1 code complete. Now working on rpi4 with MQTT.
13 ++ 2021.05.13: RaspberryPi4 v0.1 code complete. with MQTT. + Pico code bug fix.
14 ++ 2021.05.13: Fritzing design add.
15 ++ 2021.05.16: RPI4 Code update
16 ++ 2021.05.22: 3D Modeling file add.(Ender3 Pro)
17 ++ 2021.05.25: 3D Printer gcode file updated.(Ender3 Pro+PLA)
...\ No newline at end of file ...\ No newline at end of file
No preview for this file type
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
1 +# RaspberryPi4용 코드
2 +
3 +- rpi.py
4 +```
5 +라즈베리파이 메인코드
6 +```
7 +- serverside_mqtt_stest.py
8 +```
9 +server에서 데이터 보낼 예제
10 +```
11 +- serverside_mqtt_rtest.py
12 +```
13 +server에서 수신한 데이터
14 +```
15 +python rpi.py동작 후, test코드 활용해서 테스트 가능
1 +paho-mqtt
...\ No newline at end of file ...\ No newline at end of file
1 +import paho.mqtt.client as mqtt
2 +import paho.mqtt.publish as publish
3 +
4 +from bluetooth import *
5 +import time
6 +
7 +MQTT_BLOCK = False
8 +
9 +BT_MAC_ADDRESS = '00:18:91:D8:24:39'
10 +MED_BOTT_NO = '1'
11 +
12 +client_socket = BluetoothSocket( RFCOMM )
13 +client_mqtt = mqtt.Client()
14 +
15 +# --------------------------------------------------- #
16 +# INTERNAL FUNCTIONS
17 +# --------------------------------------------------- #
18 +def _send_data(msg:str):
19 + ''' Bluetooth를 통해 데이터를 송신한다
20 + '''
21 + client_socket.send(msg)
22 +
23 +def _recv_data():
24 + ''' Bluetooth를 통해 데이터를 수신한다
25 + '''
26 + # 소켓에 2초간 받을 수 있는 시간을 준다
27 + client_socket.settimeout(2)
28 +
29 + # 데이터 받을 변수
30 + data = ''
31 +
32 + try:
33 + timeout_start = time.time()
34 + timeout = 2
35 + while time.time() < timeout_start + timeout:
36 + data += client_socket.recv(1024).decode('utf-8')
37 + except:
38 + print('INFO: DATA RECV TIMEOUT')
39 + finally:
40 + return data
41 +
42 +
43 +def _sub_mqtt(client, userdata, flags, rc):
44 + ''' MQTT에서 subscribe한다
45 + '''
46 + print("Connected with result code "+str(rc))
47 + client.subscribe(f'bottle/1/stb')
48 +
49 +def _work_mqtt(client, userdata, msg):
50 + ''' MQTT에서 데이터를 받으면 알맞게 로직을 수행한다
51 + '''
52 + print('DOING SOMETHING')
53 + global MQTT_BLOCK
54 + MQTT_BLOCK = True
55 +
56 + received_msg = msg.payload.decode('utf-8')
57 +
58 + data = ''
59 + data_list = []
60 +
61 + # 만약 req메시지를 받았다면
62 + if received_msg == 'req':
63 + # 데이터가 손실되어 왔을 경우 에러 처리
64 + if len(data_list[0]) == 0:
65 + data_list = []
66 + elif len(data_list[3]) == 0:
67 + data_list = []
68 + while len(data_list) != 4:
69 + _send_data('REQ')
70 + data = _recv_data()
71 + data_list = data.split('/')
72 + # 데이터가 손실되어 왔을 경우 에러 처리
73 + if len(data_list[0]) == 0:
74 + data_list = []
75 + elif len(data_list[3]) == 0:
76 + data_list = []
77 + # 데이터를 Publish한다
78 + _pub_mqtt(f'bottle/{MED_BOTT_NO}/bts', data, 'localhost')
79 +
80 + # 만약 res메시지를 받았다면
81 + elif received_msg.split('/')[0] == 'res':
82 + _send_data(received_msg.split('/')[1])
83 + data = _recv_data()
84 + data_list = data.split('/')
85 + # 데이터가 손실되어 왔을 경우 에러 처리
86 + if len(data_list[0]) == 0:
87 + data_list = []
88 + elif len(data_list[3]) == 0:
89 + data_list = []
90 +
91 + while len(data_list) != 4:
92 + _send_data('REQ')
93 + data = _recv_data()
94 + data_list = data.split('/')
95 + # 데이터가 손실되어 왔을 경우 에러 처리
96 + if len(data_list[0]) == 0:
97 + data_list = []
98 + elif len(data_list[3]) == 0:
99 + data_list = []
100 + # 데이터를 Publish한다
101 + # _pub_mqtt(f'bottle/{MED_BOTT_NO}/bts', data, 'localhost')
102 +
103 + print("DEBUG")
104 + print(data)
105 + print(data_list)
106 + print(received_msg)
107 + MQTT_BLOCK = False
108 +
109 +def _pub_mqtt(topic:str, payload:str, hostname:str):
110 + ''' MQTT를 통해 데이터를 publish한다
111 + '''
112 + publish.single(
113 + topic=topic,
114 + payload=payload,
115 + hostname=hostname)
116 +
117 +
118 +# --------------------------------------------------- #
119 +# MAIN
120 +# --------------------------------------------------- #
121 +def _run():
122 + # CONNECT BT
123 + client_socket.connect((BT_MAC_ADDRESS, 1))
124 + print('bluetooth connected!')
125 +
126 + # SUBSCRIBE MQTT
127 + client_mqtt.on_connect = _sub_mqtt
128 + client_mqtt.on_message = _work_mqtt
129 + client_mqtt.connect_async("localhost")
130 + client_mqtt.loop_start()
131 +
132 +
133 + while True:
134 + if MQTT_BLOCK is False:
135 + # 항상 데이터를 받을 상태로 있는다
136 + data = _recv_data()
137 +
138 + # 만약 데이터가 ''가 아니면 무언가 온 것이므로 처리한다
139 + if data != '':
140 + print('DATA IN')
141 + data_list = data.split('/')
142 +
143 + # 데이터가 손실되어 왔을 경우 에러 처리
144 + if len(data_list[0]) == 0:
145 + data_list = []
146 + elif len(data_list[3]) == 0:
147 + data_list = []
148 +
149 + # 만약 데이터가 불량하게 왔을 경우, 제대로 올때까지 반복시도한다
150 + while len(data_list) != 4:
151 + data = _recv_data()
152 + data_list = data.split('/')
153 + # 데이터가 손실되어 왔을 경우 에러 처리
154 + if len(data_list[0]) == 0:
155 + data_list = []
156 + elif len(data_list[3]) == 0:
157 + data_list = []
158 +
159 + # 데이터를 Publish한다
160 + _pub_mqtt(f'bottle/{MED_BOTT_NO}/bts', data, 'localhost')
161 +
162 + client_socket.close()
163 +
164 +if __name__ == '__main__':
165 + _run()
...\ No newline at end of file ...\ No newline at end of file
1 +import paho.mqtt.client as mqtt
2 +
3 +import time
4 +
5 +def on_connect(client, userdata, flags, rc):
6 + print("Connected with result code "+str(rc))
7 + client.subscribe("bottle/1/bts") # 요거 수정해서 확인하세요
8 +
9 +def on_message(client, userdata, msg):
10 + print(msg.topic)
11 + print(msg.payload.decode('utf-8'))
12 +
13 +client = mqtt.Client()
14 +client.on_connect = on_connect
15 +client.on_message = on_message
16 +
17 +client.connect_async("localhost")
18 +client.loop_start()
19 +
20 +while True:
21 + print("TESTing")
22 + time.sleep(1)
...\ No newline at end of file ...\ No newline at end of file
1 +import paho.mqtt.publish as publish
2 +
3 +# hub -> server
4 +# msgs = \
5 +# [
6 +# {
7 +# 'topic':"bottle/1/bts",
8 +# 'payload':"1/30.4/32.2/1"
9 +# }
10 +# ]
11 +
12 +# server -> hub with date
13 +# msgs = \
14 +# [
15 +# {
16 +# 'topic':"bottle/1/stb",
17 +# 'payload':"res/0513"
18 +# }
19 +# ]
20 +
21 +# server -> hub without date
22 +msgs = \
23 +[
24 + {
25 + 'topic':"bottle/1/stb",
26 + 'payload':"req"
27 + }
28 +]
29 +
30 +publish.multiple(msgs, hostname="localhost")
1 +"""
2 +MicroPython TM1637 quad 7-segment LED display driver
3 +https://github.com/mcauser/micropython-tm1637
4 +MIT License
5 +Copyright (c) 2016 Mike Causer
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to deal
8 +in the Software without restriction, including without limitation the rights
9 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 +copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 +SOFTWARE.
21 +"""
22 +
23 +from micropython import const
24 +from machine import Pin
25 +from time import sleep_us, sleep_ms
26 +
27 +TM1637_CMD1 = const(64) # 0x40 data command
28 +TM1637_CMD2 = const(192) # 0xC0 address command
29 +TM1637_CMD3 = const(128) # 0x80 display control command
30 +TM1637_DSP_ON = const(8) # 0x08 display on
31 +TM1637_DELAY = const(10) # 10us delay between clk/dio pulses
32 +TM1637_MSB = const(128) # msb is the decimal point or the colon depending on your display
33 +
34 +# 0-9, a-z, blank, dash, star
35 +_SEGMENTS = bytearray(b'\x3F\x06\x5B\x4F\x66\x6D\x7D\x07\x7F\x6F\x77\x7C\x39\x5E\x79\x71\x3D\x76\x06\x1E\x76\x38\x55\x54\x3F\x73\x67\x50\x6D\x78\x3E\x1C\x2A\x76\x6E\x5B\x00\x40\x63')
36 +
37 +class TM1637(object):
38 + """Library for quad 7-segment LED modules based on the TM1637 LED driver."""
39 + def __init__(self, clk, dio, brightness=7):
40 + self.clk = clk
41 + self.dio = dio
42 +
43 + if not 0 <= brightness <= 7:
44 + raise ValueError("Brightness out of range")
45 + self._brightness = brightness
46 +
47 + self.clk.init(Pin.OUT, value=0)
48 + self.dio.init(Pin.OUT, value=0)
49 + sleep_us(TM1637_DELAY)
50 +
51 + self._write_data_cmd()
52 + self._write_dsp_ctrl()
53 +
54 + def _start(self):
55 + self.dio(0)
56 + sleep_us(TM1637_DELAY)
57 + self.clk(0)
58 + sleep_us(TM1637_DELAY)
59 +
60 + def _stop(self):
61 + self.dio(0)
62 + sleep_us(TM1637_DELAY)
63 + self.clk(1)
64 + sleep_us(TM1637_DELAY)
65 + self.dio(1)
66 +
67 + def _write_data_cmd(self):
68 + # automatic address increment, normal mode
69 + self._start()
70 + self._write_byte(TM1637_CMD1)
71 + self._stop()
72 +
73 + def _write_dsp_ctrl(self):
74 + # display on, set brightness
75 + self._start()
76 + self._write_byte(TM1637_CMD3 | TM1637_DSP_ON | self._brightness)
77 + self._stop()
78 +
79 + def _write_byte(self, b):
80 + for i in range(8):
81 + self.dio((b >> i) & 1)
82 + sleep_us(TM1637_DELAY)
83 + self.clk(1)
84 + sleep_us(TM1637_DELAY)
85 + self.clk(0)
86 + sleep_us(TM1637_DELAY)
87 + self.clk(0)
88 + sleep_us(TM1637_DELAY)
89 + self.clk(1)
90 + sleep_us(TM1637_DELAY)
91 + self.clk(0)
92 + sleep_us(TM1637_DELAY)
93 +
94 + def brightness(self, val=None):
95 + """Set the display brightness 0-7."""
96 + # brightness 0 = 1/16th pulse width
97 + # brightness 7 = 14/16th pulse width
98 + if val is None:
99 + return self._brightness
100 + if not 0 <= val <= 7:
101 + raise ValueError("Brightness out of range")
102 +
103 + self._brightness = val
104 + self._write_data_cmd()
105 + self._write_dsp_ctrl()
106 +
107 + def write(self, segments, pos=0):
108 + """Display up to 6 segments moving right from a given position.
109 + The MSB in the 2nd segment controls the colon between the 2nd
110 + and 3rd segments."""
111 + if not 0 <= pos <= 5:
112 + raise ValueError("Position out of range")
113 + self._write_data_cmd()
114 + self._start()
115 +
116 + self._write_byte(TM1637_CMD2 | pos)
117 + for seg in segments:
118 + self._write_byte(seg)
119 + self._stop()
120 + self._write_dsp_ctrl()
121 +
122 + def encode_digit(self, digit):
123 + """Convert a character 0-9, a-f to a segment."""
124 + return _SEGMENTS[digit & 0x0f]
125 +
126 + def encode_string(self, string):
127 + """Convert an up to 4 character length string containing 0-9, a-z,
128 + space, dash, star to an array of segments, matching the length of the
129 + source string."""
130 + segments = bytearray(len(string))
131 + for i in range(len(string)):
132 + segments[i] = self.encode_char(string[i])
133 + return segments
134 +
135 + def encode_char(self, char):
136 + """Convert a character 0-9, a-z, space, dash or star to a segment."""
137 + o = ord(char)
138 + if o == 32:
139 + return _SEGMENTS[36] # space
140 + if o == 42:
141 + return _SEGMENTS[38] # star/degrees
142 + if o == 45:
143 + return _SEGMENTS[37] # dash
144 + if o >= 65 and o <= 90:
145 + return _SEGMENTS[o-55] # uppercase A-Z
146 + if o >= 97 and o <= 122:
147 + return _SEGMENTS[o-87] # lowercase a-z
148 + if o >= 48 and o <= 57:
149 + return _SEGMENTS[o-48] # 0-9
150 + raise ValueError("Character out of range: {:d} '{:s}'".format(o, chr(o)))
151 +
152 + def hex(self, val):
153 + """Display a hex value 0x0000 through 0xffff, right aligned."""
154 + string = '{:04x}'.format(val & 0xffff)
155 + self.write(self.encode_string(string))
156 +
157 + def number(self, num):
158 + """Display a numeric value -999 through 9999, right aligned."""
159 + # limit to range -999 to 9999
160 + num = max(-999, min(num, 9999))
161 + string = '{0: >4d}'.format(num)
162 + self.write(self.encode_string(string))
163 +
164 + def numbers(self, num1, num2, colon=True):
165 + """Display two numeric values -9 through 99, with leading zeros
166 + and separated by a colon."""
167 + num1 = max(-9, min(num1, 99))
168 + num2 = max(-9, min(num2, 99))
169 + segments = self.encode_string('{0:0>2d}{1:0>2d}'.format(num1, num2))
170 + if colon:
171 + segments[1] |= 0x80 # colon on
172 + self.write(segments)
173 +
174 + def temperature(self, num):
175 + if num < -9:
176 + self.show('lo') # low
177 + elif num > 99:
178 + self.show('hi') # high
179 + else:
180 + string = '{0: >2d}'.format(num)
181 + self.write(self.encode_string(string))
182 + self.write([_SEGMENTS[38], _SEGMENTS[12]], 2) # degrees C
183 +
184 + def show(self, string, colon=False):
185 + segments = self.encode_string(string)
186 + if len(segments) > 1 and colon:
187 + segments[1] |= 128
188 + self.write(segments[:4])
189 +
190 + def scroll(self, string, delay=250):
191 + segments = string if isinstance(string, list) else self.encode_string(string)
192 + data = [0] * 8
193 + data[4:0] = list(segments)
194 + for i in range(len(segments) + 5):
195 + self.write(data[0+i:4+i])
196 + sleep_ms(delay)
197 +
198 +
199 +class TM1637Decimal(TM1637):
200 + """Library for quad 7-segment LED modules based on the TM1637 LED driver.
201 + This class is meant to be used with decimal display modules (modules
202 + that have a decimal point after each 7-segment LED).
203 + """
204 +
205 + def encode_string(self, string):
206 + """Convert a string to LED segments.
207 + Convert an up to 4 character length string containing 0-9, a-z,
208 + space, dash, star and '.' to an array of segments, matching the length of
209 + the source string."""
210 + segments = bytearray(len(string.replace('.','')))
211 + j = 0
212 + for i in range(len(string)):
213 + if string[i] == '.' and j > 0:
214 + segments[j-1] |= TM1637_MSB
215 + continue
216 + segments[j] = self.encode_char(string[i])
217 + j += 1
218 + return segments
1 +import uos
2 +import machine
3 +import utime
4 +
5 +uart0 = machine.UART(0,baudrate=9600)
6 +
7 +# --------------------------------------------------- #
8 +# INTERNAL FUNCTIONS
9 +# --------------------------------------------------- #
10 +def _clartBuf(uart=uart0):
11 + ''' Clear Buffer
12 + '''
13 + while uart.any():
14 + print(uart.read(1))
15 +
16 +# --------------------------------------------------- #
17 +# FUNCTIONS
18 +# --------------------------------------------------- #
19 +def send_data_bt(sdata:str):
20 + ''' Send string data using Bluetooth
21 + '''
22 + _clartBuf()
23 + uart0.write(sdata)
24 +
25 +
26 +def recv_data_bt():
27 + ''' Receive string data using Bluetooth
28 + '''
29 + _clartBuf()
30 + prvMills = utime.ticks_ms()
31 + received_data = ''
32 +
33 + while (utime.ticks_ms()-prvMills)<2000:
34 + if uart0.any():
35 + single_data = uart0.read(1)
36 + received_data += single_data.decode('utf-8')
37 +
38 + return received_data
...\ No newline at end of file ...\ No newline at end of file
1 +''' Original code from https://www.raspberrypi.org/forums/viewtopic.php?t=303606
2 +'''
3 +import utime
4 +import rp2
5 +from rp2 import PIO, asm_pio
6 +from machine import Pin
7 +
8 +# --------------------------------------------------- #
9 +# INIT
10 +# --------------------------------------------------- #
11 +# For VCC
12 +dht_pwr = Pin(14, Pin.OUT)
13 +# For data
14 +dht_data = Pin(15, Pin.IN, Pin.PULL_UP)
15 +
16 +# Power on
17 +dht_pwr.value(1)
18 +# Create empty state
19 +sm=rp2.StateMachine(1)
20 +# Wait for DHT22 to start up
21 +utime.sleep(2)
22 +
23 +# --------------------------------------------------- #
24 +# INIT2
25 +# --------------------------------------------------- #
26 +@asm_pio(set_init=(PIO.OUT_HIGH),autopush=True, push_thresh=8) #output one byte at a time
27 +def DHT22():
28 + #drive output low for at least 20ms
29 + set(pindirs,1) #set pin to output
30 + set(pins,0) #set pin low
31 + set(y,31) #prepare countdown, y*x*100cycles
32 + label ('waity')
33 + set(x,31)
34 + label ('waitx')
35 + nop() [30]
36 + jmp(x_dec,'waitx') #decrement x reg every 100 cycles
37 + jmp(y_dec,'waity') #decrement y reg every time x reaches zero
38 +
39 + #begin reading from device
40 + set(pindirs,0) #set pin to input
41 + wait(1,pin,0) #check pin is high before starting
42 + wait(0,pin,0)
43 + wait(1,pin,0)
44 + wait(0,pin,0) #wait for start of data
45 +
46 + #read databit
47 + label('readdata')
48 + set(x,21) #reset x register to count down from 20
49 + wait(1,pin,0) #wait for high signal
50 + label('countdown')
51 + jmp(pin,'continue') #if pin still high continue counting
52 + #pin is low before countdown is complete - bit '0' detected
53 + set(y,0)
54 + in_(y, 1) #shift '0' into the isr
55 + jmp('readdata') #read the next bit
56 +
57 + label('continue')
58 + jmp(x_dec,'countdown') #decrement x reg and continue counting if x!=0
59 + #pin is still high after countdown complete - bit '1' detected
60 + set(y,1)
61 + in_(y, 1) #shift one bit into the isr
62 + wait(0,pin,0) #wait for low signal (next bit)
63 + jmp('readdata') #read the next bit
64 +
65 +
66 +# --------------------------------------------------- #
67 +# FUNCTIONS
68 +# --------------------------------------------------- #
69 +def work_dht():
70 + data=[]
71 + total=0
72 + sm.init(DHT22,freq=1600000,set_base=dht_data,in_base=dht_data,jmp_pin=dht_data)
73 + sm.active(1)
74 + for i in range(5): #data should be 40 bits (5 bytes) long
75 + data.append(sm.get()) #read byte
76 +
77 + #check checksum (lowest 8 bits of the sum of the first 4 bytes)
78 + for i in range(4):
79 + total=total+data[i]
80 + if((total & 255) == data[4]):
81 + humidity=((data[0]<<8) + data[1])/10.0
82 + temperature=(((data[2] &0x7f) << 8) + data[3]) /10.0
83 + if (data[2] & 0x80) == 0x80:
84 + temperature = -temperature
85 + return [humidity, temperature]
86 + else:
87 + return False
...\ No newline at end of file ...\ No newline at end of file
1 +import tm1637
2 +from machine import Pin
3 +from utime import sleep
4 +display4 = tm1637.TM1637(clk=Pin(12), dio=Pin(13))
5 +
6 +# --------------------------------------------------- #
7 +# FUNCTIONS
8 +# --------------------------------------------------- #
9 +def work_tm1637(data:str):
10 + display4.show(data)
11 +
12 +def off_tm1637():
13 + display4.show(' ')
14 +
15 +# # Show a word
16 +# mydisplay.show("Pico")
17 +# sleep(1)
18 +
19 +# #blank the screen
20 +# mydisplay.show(" ")
21 +# sleep(1)
22 +
23 +# #show numbers
24 +# mydisplay.number(-123)
25 +# sleep(1)
26 +
27 +# #show a time with colon
28 +# mydisplay.numbers(12,59)
29 +# sleep(1)
30 +
31 +# #adjust the brightness to make it lower
32 +# mydisplay.brightness(0)
33 +# sleep(1)
34 +
35 +# #show scrolling text
36 +# mydisplay.scroll("Hello World 123", delay=200)
37 +# sleep(1)
38 +
39 +# #show temperature
40 +# mydisplay.temperature(99)
41 +# sleep(1)
42 +
43 +# #blank the screen again
44 +# mydisplay.show(" ")
...\ No newline at end of file ...\ No newline at end of file
1 +import array, utime
2 +from machine import Pin
3 +import rp2
4 +
5 +import neopixel
6 +import dht
7 +import bluetoooth as bto
8 +import ultrasonic
9 +import reed
10 +import display4
11 +
12 +# --------------------------------------------------- #
13 +# FUNCTIONS
14 +# --------------------------------------------------- #
15 +def _collect_sensor_datas(reed_data:int) -> str:
16 + # Collect Humidity, Temperature
17 + dht_data = dht.work_dht()
18 + if dht_data == False:
19 + dht_data = [0,0]
20 + # Collect Ultrasonic distance
21 + ultrasonic_data = ultrasonic.work_sr04()
22 + # Make data string
23 + send_data_str = str(reed_data) + '/' + str(dht_data[1]) + '/' + str(dht_data[0]) + '/' + str(ultrasonic_data)
24 +
25 + return send_data_str
26 +
27 +# --------------------------------------------------- #
28 +# LOOP ENTRYPOINT
29 +# --------------------------------------------------- #
30 +def _run():
31 + # INIT REED STATE
32 + reed_data = -1
33 + # LOOP
34 + while True:
35 + # ------------------------------------------- #
36 + # DEFAULT LOOP
37 + # ------------------------------------------- #
38 + # Get data using BT(Standby)
39 + input_data = bto.recv_data_bt()
40 +
41 + # Get reed data from reed sensor
42 + current_reed_data = reed.work_reed()
43 +
44 + # ------------------------------------------- #
45 + # IF CONDITION MET
46 + # ------------------------------------------- #
47 + if input_data != '' or reed_data != current_reed_data:
48 + # Refine BT data
49 + input_data = input_data.strip()
50 + # Test code
51 + print('INPUT FOUND ', input_data)
52 +
53 + # IF INPUT MEANS GET MESSAGE or MEDICINE LID STATUS CHANGED
54 + if input_data == 'REQ' or reed_data != current_reed_data:
55 + # Send data using BT
56 + bto.send_data_bt(_collect_sensor_datas(current_reed_data))
57 + else:
58 + # Refine BT data
59 + input_data = input_data.strip()
60 + display4.work_tm1637(input_data)
61 + neopixel.work_led()
62 + display4.off_tm1637()
63 + # Send data using BT
64 + bto.send_data_bt(_collect_sensor_datas(current_reed_data))
65 +
66 + # Update reed state
67 + reed_data = current_reed_data
68 +
69 +
70 +
71 +if __name__ == '__main__':
72 + _run()
...\ No newline at end of file ...\ No newline at end of file
1 +''' Original code from https://core-electronics.com.au/tutorials/how-to-use-ws2812b-rgb-leds-with-raspberry-pi-pico.html
2 +'''
3 +import array, utime
4 +from machine import Pin
5 +import rp2
6 +
7 +# --------------------------------------------------- #
8 +# INIT
9 +# --------------------------------------------------- #
10 +NUM_LEDS = 8
11 +PIN_NUM = 22
12 +
13 +BLACK = (0, 0, 0)
14 +RED = (255, 0, 0)
15 +YELLOW = (255, 150, 0)
16 +GREEN = (0, 255, 0)
17 +CYAN = (0, 255, 255)
18 +BLUE = (0, 0, 255)
19 +PURPLE = (180, 0, 255)
20 +WHITE = (255, 255, 255)
21 +COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE, BLACK)
22 +
23 +# --------------------------------------------------- #
24 +# INIT2
25 +# --------------------------------------------------- #
26 +@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
27 +def ws2812():
28 + T1 = 2
29 + T2 = 5
30 + T3 = 3
31 + wrap_target()
32 + label("bitloop")
33 + out(x, 1) .side(0) [T3 - 1]
34 + jmp(not_x, "do_zero") .side(1) [T1 - 1]
35 + jmp("bitloop") .side(1) [T2 - 1]
36 + label("do_zero")
37 + nop() .side(0) [T2 - 1]
38 + wrap()
39 +
40 +# Create the StateMachine with the ws2812 program, outputting on pin
41 +sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM))
42 +# Start the StateMachine, it will wait for data on its FIFO.
43 +sm.active(1)
44 +# Display a pattern on the LEDs via an array of LED RGB values.
45 +ar = array.array("I", [0 for _ in range(NUM_LEDS)])
46 +
47 +# --------------------------------------------------- #
48 +# INTERNAL FUNCTIONS
49 +# --------------------------------------------------- #
50 +def _pixels_show(brightness:int = 0.2):
51 + dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)])
52 + for i,c in enumerate(ar):
53 + r = int(((c >> 8) & 0xFF) * brightness)
54 + g = int(((c >> 16) & 0xFF) * brightness)
55 + b = int((c & 0xFF) * brightness)
56 + dimmer_ar[i] = (g<<16) + (r<<8) + b
57 + sm.put(dimmer_ar, 8)
58 + utime.sleep_ms(10)
59 +
60 +def _pixels_set(i, color):
61 + ar[i] = (color[1]<<16) + (color[0]<<8) + color[2]
62 +
63 +def _pixels_fill(color):
64 + for i in range(len(ar)):
65 + _pixels_set(i, color)
66 +
67 +
68 +# --------------------------------------------------- #
69 +# FUNCTIONS
70 +# --------------------------------------------------- #
71 +def work_led(brightness:int = 0.2):
72 + for color in COLORS:
73 + _pixels_fill(color)
74 + _pixels_show(brightness)
75 + utime.sleep(0.4)
1 +from machine import Pin, Signal
2 +
3 +data_pin = Pin(16, Pin.IN)
4 +
5 +# --------------------------------------------------- #
6 +# FUNCTIONS
7 +# --------------------------------------------------- #
8 +def work_reed() -> int:
9 + # 1 = Lid opened, 0 = Lid closed
10 + return data_pin.value()
1 +''' Original code from https://www.iottrends.tech/blog/how-to-use-ultrasonic-sensor-with-raspberry-pi-pico/
2 +'''
3 +from machine import Pin
4 +import utime
5 +trigger = Pin(26, Pin.OUT)
6 +echo = Pin(27, Pin.IN)
7 +
8 +# --------------------------------------------------- #
9 +# FUNCTIONS
10 +# --------------------------------------------------- #
11 +def work_sr04():
12 + trigger.low()
13 + utime.sleep_us(2)
14 + trigger.high()
15 + utime.sleep_us(5)
16 + trigger.low()
17 + while echo.value() == 0:
18 + signaloff = utime.ticks_us()
19 + while echo.value() == 1:
20 + signalon = utime.ticks_us()
21 + timepassed = signalon - signaloff
22 + distance = (timepassed * 0.0330) / 2
23 +
24 + return distance
1 +import uos
2 +import machine
3 +import utime
4 +
5 +uart0 = machine.UART(0,baudrate=9600)
6 +
7 +def _clartBuf(uart=uart0):
8 + print("Clear UART buffer "+ str(uart))
9 + while uart.any():
10 + print(uart.read(1))
11 +
12 +
13 +def send_data_bt(sdata:str):
14 + _clartBuf()
15 + uart0.write(sdata)
16 +
17 +
18 +def recv_data_bt():
19 + _clartBuf()
20 + prvMills = utime.ticks_ms()
21 + received_data = ''
22 +
23 + while (utime.ticks_ms()-prvMills)<2000:
24 + if uart0.any():
25 + single_data = uart0.read(1)
26 + received_data += single_data.decode('utf-8')
27 +
28 + return received_data
1 +import utime
2 +import rp2
3 +from rp2 import PIO, asm_pio
4 +from machine import Pin
5 +
6 +dht_pwr = Pin(14, Pin.OUT) #connect GPIO 14 to '+' on DHT11
7 +dht_data = Pin(15, Pin.IN, Pin.PULL_UP) #connect GPIO 15 to 'out' on DHT11
8 +
9 +dht_pwr.value(1) #power on DHT11
10 +sm=rp2.StateMachine(1) #create empty state machine
11 +utime.sleep(2) #wait for DHT11 to start up
12 +
13 +@asm_pio(set_init=(PIO.OUT_HIGH),autopush=True, push_thresh=8) #output one byte at a time
14 +def DHT22():
15 + #drive output low for at least 20ms
16 + set(pindirs,1) #set pin to output
17 + set(pins,0) #set pin low
18 + set(y,31) #prepare countdown, y*x*100cycles
19 + label ('waity')
20 + set(x,31)
21 + label ('waitx')
22 + nop() [30]
23 + jmp(x_dec,'waitx') #decrement x reg every 100 cycles
24 + jmp(y_dec,'waity') #decrement y reg every time x reaches zero
25 +
26 + #begin reading from device
27 + set(pindirs,0) #set pin to input
28 + wait(1,pin,0) #check pin is high before starting
29 + wait(0,pin,0)
30 + wait(1,pin,0)
31 + wait(0,pin,0) #wait for start of data
32 +
33 + #read databit
34 + label('readdata')
35 + set(x,21) #reset x register to count down from 20
36 + wait(1,pin,0) #wait for high signal
37 + label('countdown')
38 + jmp(pin,'continue') #if pin still high continue counting
39 + #pin is low before countdown is complete - bit '0' detected
40 + set(y,0)
41 + in_(y, 1) #shift '0' into the isr
42 + jmp('readdata') #read the next bit
43 +
44 + label('continue')
45 + jmp(x_dec,'countdown') #decrement x reg and continue counting if x!=0
46 + #pin is still high after countdown complete - bit '1' detected
47 + set(y,1)
48 + in_(y, 1) #shift one bit into the isr
49 + wait(0,pin,0) #wait for low signal (next bit)
50 + jmp('readdata') #read the next bit
51 +
52 +
53 +# --------------------------------------------------- #
54 +# ENTRYPOINT
55 +# --------------------------------------------------- #
56 +def work_dht():
57 + print("DHT22 WORKING")
58 + data=[]
59 + total=0
60 + sm.init(DHT22,freq=1600000,set_base=dht_data,in_base=dht_data,jmp_pin=dht_data) #start state machine
61 + #state machine frequency adjusted so that PIO countdown during 'readdata' ends somewhere between the
62 + #duration of a '0' and a '1' high signal
63 + sm.active(1)
64 + for i in range(5): #data should be 40 bits (5 bytes) long
65 + data.append(sm.get()) #read byte
66 +
67 + print("data: " + str(data))
68 +
69 + #check checksum (lowest 8 bits of the sum of the first 4 bytes)
70 + for i in range(4):
71 + total=total+data[i]
72 + if((total & 255) == data[4]):
73 + humidity=((data[0]<<8) + data[1])/10.0 #DHT11 provides integer humidity (no decimal part)
74 + temperature=(((data[2] &0x7f) << 8) + data[3]) /10.0 #DHT11 provides signed integer temperature (no decimal part)
75 + if (data[2] & 0x80) == 0x80:
76 + temperature = -temperature
77 + return [humidity, temperature]
78 + else:
79 + return False
1 +import tm1637
2 +from machine import Pin
3 +from utime import sleep
4 +display4 = tm1637.TM1637(clk=Pin(12), dio=Pin(13))
5 +
6 +# --------------------------------------------------- #
7 +# FUNCTIONS
8 +# --------------------------------------------------- #
9 +def work_tm1637(data:str):
10 + display4.show(data)
11 +
12 +def off_tm1637():
13 + display4.show(' ')
1 +import array, utime
2 +from machine import Pin
3 +import rp2
4 +
5 +import neopixel
6 +import dht
7 +import bluetoooth as bto
8 +import ultrasonic
9 +import reed
10 +import display4
11 +
12 +# --------------------------------------------------- #
13 +# FUNCTIONS
14 +# --------------------------------------------------- #
15 +def _collect_sensor_datas(reed_data:int) -> str:
16 + # Collect Humidity, Temperature
17 + dht_data = dht.work_dht()
18 + if dht_data == False:
19 + dht_data = [0,0]
20 + # Collect Ultrasonic distance
21 + ultrasonic_data = ultrasonic.work_sr04()
22 + # Make data string
23 + send_data_str = str(reed_data) + '/' + str(dht_data[1]) + '/' + str(dht_data[0]) + '/' + str(ultrasonic_data)
24 +
25 + return send_data_str
26 +
27 +# --------------------------------------------------- #
28 +# LOOP ENTRYPOINT
29 +# --------------------------------------------------- #
30 +def _run():
31 + # INIT REED STATE
32 + reed_data = -1
33 + display4.off_tm1637()
34 + # LOOP
35 + while True:
36 + # ------------------------------------------- #
37 + # DEFAULT LOOP
38 + # ------------------------------------------- #
39 + # Get data using BT(Standby)
40 + input_data = bto.recv_data_bt()
41 +
42 + # Get reed data from reed sensor
43 + current_reed_data = reed.work_reed()
44 +
45 + # ------------------------------------------- #
46 + # IF CONDITION MET
47 + # ------------------------------------------- #
48 + if input_data != '' or reed_data != current_reed_data:
49 + # Refine BT data
50 + input_data = input_data.strip()
51 + # Test code
52 + print('INPUT FOUND ', input_data)
53 +
54 + # IF INPUT MEANS GET MESSAGE or MEDICINE LID STATUS CHANGED
55 + if input_data == 'REQ' or reed_data != current_reed_data:
56 + # Send data using BT
57 + bto.send_data_bt(_collect_sensor_datas(reed_data))
58 + else:
59 + # Refine BT data
60 + input_data = input_data.strip()
61 + display4.work_tm1637(input_data)
62 + neopixel.work_led()
63 + display4.off_tm1637()
64 + # Send data using BT
65 + bto.send_data_bt(_collect_sensor_datas(reed_data))
66 +
67 + # Update reed state
68 + reed_data = current_reed_data
69 +
70 +
71 +
72 +if __name__ == '__main__':
73 + _run()
1 +import array, utime
2 +from machine import Pin
3 +import rp2
4 +
5 +NUM_LEDS = 8
6 +PIN_NUM = 22
7 +
8 +BLACK = (0, 0, 0)
9 +RED = (255, 0, 0)
10 +YELLOW = (255, 150, 0)
11 +GREEN = (0, 255, 0)
12 +CYAN = (0, 255, 255)
13 +BLUE = (0, 0, 255)
14 +PURPLE = (180, 0, 255)
15 +WHITE = (255, 255, 255)
16 +COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE, BLACK)
17 +
18 +@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
19 +def ws2812():
20 + T1 = 2
21 + T2 = 5
22 + T3 = 3
23 + wrap_target()
24 + label("bitloop")
25 + out(x, 1) .side(0) [T3 - 1]
26 + jmp(not_x, "do_zero") .side(1) [T1 - 1]
27 + jmp("bitloop") .side(1) [T2 - 1]
28 + label("do_zero")
29 + nop() .side(0) [T2 - 1]
30 + wrap()
31 +
32 +# Create the StateMachine with the ws2812 program, outputting on pin
33 +sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM))
34 +# Start the StateMachine, it will wait for data on its FIFO.
35 +sm.active(1)
36 +# Display a pattern on the LEDs via an array of LED RGB values.
37 +ar = array.array("I", [0 for _ in range(NUM_LEDS)])
38 +
39 +# --------------------------------------------------- #
40 +# FUNCTIONS
41 +# --------------------------------------------------- #
42 +def _pixels_show(brightness:int = 0.2):
43 + dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)])
44 + for i,c in enumerate(ar):
45 + r = int(((c >> 8) & 0xFF) * brightness)
46 + g = int(((c >> 16) & 0xFF) * brightness)
47 + b = int((c & 0xFF) * brightness)
48 + dimmer_ar[i] = (g<<16) + (r<<8) + b
49 + sm.put(dimmer_ar, 8)
50 + utime.sleep_ms(10)
51 +
52 +def _pixels_set(i, color):
53 + ar[i] = (color[1]<<16) + (color[0]<<8) + color[2]
54 +
55 +def _pixels_fill(color):
56 + for i in range(len(ar)):
57 + _pixels_set(i, color)
58 +
59 +
60 +# --------------------------------------------------- #
61 +# ENTRYPOINT
62 +# --------------------------------------------------- #
63 +def work_led(brightness:int = 0.2):
64 + print("WS2812B WORKING")
65 + for color in COLORS:
66 + _pixels_fill(color)
67 + _pixels_show(brightness)
68 + utime.sleep(0.4)
69 +
1 +from machine import Pin, Signal
2 +
3 +data_pin = Pin(16, Pin.IN)
4 +
5 +# --------------------------------------------------- #
6 +# FUNCTIONS
7 +# --------------------------------------------------- #
8 +def work_reed() -> int:
9 + # 1 = Lid opened, 0 = Lid closed
10 + return data_pin.value()
11 +
1 +"""
2 +MicroPython TM1637 quad 7-segment LED display driver
3 +https://github.com/mcauser/micropython-tm1637
4 +MIT License
5 +Copyright (c) 2016 Mike Causer
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to deal
8 +in the Software without restriction, including without limitation the rights
9 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 +copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 +SOFTWARE.
21 +"""
22 +
23 +from micropython import const
24 +from machine import Pin
25 +from time import sleep_us, sleep_ms
26 +
27 +TM1637_CMD1 = const(64) # 0x40 data command
28 +TM1637_CMD2 = const(192) # 0xC0 address command
29 +TM1637_CMD3 = const(128) # 0x80 display control command
30 +TM1637_DSP_ON = const(8) # 0x08 display on
31 +TM1637_DELAY = const(10) # 10us delay between clk/dio pulses
32 +TM1637_MSB = const(128) # msb is the decimal point or the colon depending on your display
33 +
34 +# 0-9, a-z, blank, dash, star
35 +_SEGMENTS = bytearray(b'\x3F\x06\x5B\x4F\x66\x6D\x7D\x07\x7F\x6F\x77\x7C\x39\x5E\x79\x71\x3D\x76\x06\x1E\x76\x38\x55\x54\x3F\x73\x67\x50\x6D\x78\x3E\x1C\x2A\x76\x6E\x5B\x00\x40\x63')
36 +
37 +class TM1637(object):
38 + """Library for quad 7-segment LED modules based on the TM1637 LED driver."""
39 + def __init__(self, clk, dio, brightness=7):
40 + self.clk = clk
41 + self.dio = dio
42 +
43 + if not 0 <= brightness <= 7:
44 + raise ValueError("Brightness out of range")
45 + self._brightness = brightness
46 +
47 + self.clk.init(Pin.OUT, value=0)
48 + self.dio.init(Pin.OUT, value=0)
49 + sleep_us(TM1637_DELAY)
50 +
51 + self._write_data_cmd()
52 + self._write_dsp_ctrl()
53 +
54 + def _start(self):
55 + self.dio(0)
56 + sleep_us(TM1637_DELAY)
57 + self.clk(0)
58 + sleep_us(TM1637_DELAY)
59 +
60 + def _stop(self):
61 + self.dio(0)
62 + sleep_us(TM1637_DELAY)
63 + self.clk(1)
64 + sleep_us(TM1637_DELAY)
65 + self.dio(1)
66 +
67 + def _write_data_cmd(self):
68 + # automatic address increment, normal mode
69 + self._start()
70 + self._write_byte(TM1637_CMD1)
71 + self._stop()
72 +
73 + def _write_dsp_ctrl(self):
74 + # display on, set brightness
75 + self._start()
76 + self._write_byte(TM1637_CMD3 | TM1637_DSP_ON | self._brightness)
77 + self._stop()
78 +
79 + def _write_byte(self, b):
80 + for i in range(8):
81 + self.dio((b >> i) & 1)
82 + sleep_us(TM1637_DELAY)
83 + self.clk(1)
84 + sleep_us(TM1637_DELAY)
85 + self.clk(0)
86 + sleep_us(TM1637_DELAY)
87 + self.clk(0)
88 + sleep_us(TM1637_DELAY)
89 + self.clk(1)
90 + sleep_us(TM1637_DELAY)
91 + self.clk(0)
92 + sleep_us(TM1637_DELAY)
93 +
94 + def brightness(self, val=None):
95 + """Set the display brightness 0-7."""
96 + # brightness 0 = 1/16th pulse width
97 + # brightness 7 = 14/16th pulse width
98 + if val is None:
99 + return self._brightness
100 + if not 0 <= val <= 7:
101 + raise ValueError("Brightness out of range")
102 +
103 + self._brightness = val
104 + self._write_data_cmd()
105 + self._write_dsp_ctrl()
106 +
107 + def write(self, segments, pos=0):
108 + """Display up to 6 segments moving right from a given position.
109 + The MSB in the 2nd segment controls the colon between the 2nd
110 + and 3rd segments."""
111 + if not 0 <= pos <= 5:
112 + raise ValueError("Position out of range")
113 + self._write_data_cmd()
114 + self._start()
115 +
116 + self._write_byte(TM1637_CMD2 | pos)
117 + for seg in segments:
118 + self._write_byte(seg)
119 + self._stop()
120 + self._write_dsp_ctrl()
121 +
122 + def encode_digit(self, digit):
123 + """Convert a character 0-9, a-f to a segment."""
124 + return _SEGMENTS[digit & 0x0f]
125 +
126 + def encode_string(self, string):
127 + """Convert an up to 4 character length string containing 0-9, a-z,
128 + space, dash, star to an array of segments, matching the length of the
129 + source string."""
130 + segments = bytearray(len(string))
131 + for i in range(len(string)):
132 + segments[i] = self.encode_char(string[i])
133 + return segments
134 +
135 + def encode_char(self, char):
136 + """Convert a character 0-9, a-z, space, dash or star to a segment."""
137 + o = ord(char)
138 + if o == 32:
139 + return _SEGMENTS[36] # space
140 + if o == 42:
141 + return _SEGMENTS[38] # star/degrees
142 + if o == 45:
143 + return _SEGMENTS[37] # dash
144 + if o >= 65 and o <= 90:
145 + return _SEGMENTS[o-55] # uppercase A-Z
146 + if o >= 97 and o <= 122:
147 + return _SEGMENTS[o-87] # lowercase a-z
148 + if o >= 48 and o <= 57:
149 + return _SEGMENTS[o-48] # 0-9
150 + raise ValueError("Character out of range: {:d} '{:s}'".format(o, chr(o)))
151 +
152 + def hex(self, val):
153 + """Display a hex value 0x0000 through 0xffff, right aligned."""
154 + string = '{:04x}'.format(val & 0xffff)
155 + self.write(self.encode_string(string))
156 +
157 + def number(self, num):
158 + """Display a numeric value -999 through 9999, right aligned."""
159 + # limit to range -999 to 9999
160 + num = max(-999, min(num, 9999))
161 + string = '{0: >4d}'.format(num)
162 + self.write(self.encode_string(string))
163 +
164 + def numbers(self, num1, num2, colon=True):
165 + """Display two numeric values -9 through 99, with leading zeros
166 + and separated by a colon."""
167 + num1 = max(-9, min(num1, 99))
168 + num2 = max(-9, min(num2, 99))
169 + segments = self.encode_string('{0:0>2d}{1:0>2d}'.format(num1, num2))
170 + if colon:
171 + segments[1] |= 0x80 # colon on
172 + self.write(segments)
173 +
174 + def temperature(self, num):
175 + if num < -9:
176 + self.show('lo') # low
177 + elif num > 99:
178 + self.show('hi') # high
179 + else:
180 + string = '{0: >2d}'.format(num)
181 + self.write(self.encode_string(string))
182 + self.write([_SEGMENTS[38], _SEGMENTS[12]], 2) # degrees C
183 +
184 + def show(self, string, colon=False):
185 + segments = self.encode_string(string)
186 + if len(segments) > 1 and colon:
187 + segments[1] |= 128
188 + self.write(segments[:4])
189 +
190 + def scroll(self, string, delay=250):
191 + segments = string if isinstance(string, list) else self.encode_string(string)
192 + data = [0] * 8
193 + data[4:0] = list(segments)
194 + for i in range(len(segments) + 5):
195 + self.write(data[0+i:4+i])
196 + sleep_ms(delay)
197 +
198 +
199 +class TM1637Decimal(TM1637):
200 + """Library for quad 7-segment LED modules based on the TM1637 LED driver.
201 + This class is meant to be used with decimal display modules (modules
202 + that have a decimal point after each 7-segment LED).
203 + """
204 +
205 + def encode_string(self, string):
206 + """Convert a string to LED segments.
207 + Convert an up to 4 character length string containing 0-9, a-z,
208 + space, dash, star and '.' to an array of segments, matching the length of
209 + the source string."""
210 + segments = bytearray(len(string.replace('.','')))
211 + j = 0
212 + for i in range(len(string)):
213 + if string[i] == '.' and j > 0:
214 + segments[j-1] |= TM1637_MSB
215 + continue
216 + segments[j] = self.encode_char(string[i])
217 + j += 1
218 + return segments
219 +
220 +
1 +''' Original code from https://www.iottrends.tech/blog/how-to-use-ultrasonic-sensor-with-raspberry-pi-pico/
2 +'''
3 +from machine import Pin
4 +import utime
5 +trigger = Pin(26, Pin.OUT)
6 +echo = Pin(27, Pin.IN)
7 +
8 +# --------------------------------------------------- #
9 +# FUNCTIONS
10 +# --------------------------------------------------- #
11 +def work_sr04():
12 + trigger.low()
13 + utime.sleep_us(2)
14 + trigger.high()
15 + utime.sleep_us(5)
16 + trigger.low()
17 + while echo.value() == 0:
18 + signaloff = utime.ticks_us()
19 + while echo.value() == 1:
20 + signalon = utime.ticks_us()
21 + timepassed = signalon - signaloff
22 + distance = (timepassed * 0.0330) / 2
23 +
24 + return distance
25 +
1 +
2 +#include <SoftwareSerial.h>
3 +#include <DHT.h>
4 +#include <TM1637Display.h>
5 +#include <Adafruit_NeoPixel.h>
6 +#include <string.h>
7 +
8 +//-------------Bluetooth--------------//
9 +#define BLUETXPIN 2
10 +#define BLUERXPIN 3
11 +
12 +const byte numChars = 15;
13 +char inputdata[numChars]; // an array to store the received data
14 +
15 +boolean newData = false;
16 +
17 +//--------Temperature, Humidity--------//
18 +#define DHTPIN A2
19 +#define DHTTYPE DHT22
20 +
21 +DHT dht(DHTPIN, DHTTYPE);
22 +
23 +//-------------Ultrasonic-------------//
24 +#define USTRIGPIN A0
25 +#define USECHOPIN A1
26 +
27 +long duration;
28 +long distance;
29 +
30 +//--------------Magnetic--------------//
31 +#define MAGPIN 13
32 +int mag_value = 0;
33 +
34 +SoftwareSerial wirelessSerial(BLUETXPIN, BLUERXPIN);
35 +
36 +//--------------7Segment--------------//
37 +#define TM1637CLKPIN 5
38 +#define TM1637DIOPIN 4
39 +
40 +TM1637Display display = TM1637Display(TM1637CLKPIN, TM1637DIOPIN);
41 +
42 +// All segments on:
43 +const uint8_t data[] = {0xff, 0xff, 0xff, 0xff};
44 +// All segments off:
45 +const uint8_t blank[] = {0x00, 0x00, 0x00, 0x00};
46 +
47 +//--------------NeoPixel--------------//
48 +#define NEOPIXELPIN 6
49 +#define NUMLED 8
50 +Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMLED, NEOPIXELPIN, NEO_GRB + NEO_KHZ800);
51 +
52 +//------------Entrypoint--------------//
53 +void setup() {
54 + // Temp, Hum
55 + dht.begin();
56 +
57 + // Ultrasonic
58 + pinMode(USTRIGPIN, OUTPUT);
59 + pinMode(USECHOPIN, INPUT);
60 +
61 + // Magnetic
62 + pinMode(MAGPIN, INPUT);
63 +
64 + // Bluetooth
65 + wirelessSerial.begin(9600);
66 +
67 + // 7Segment
68 + display.clear();
69 + display.setBrightness(7);
70 +
71 + // NeoPixel
72 + strip.begin();
73 + strip.show();
74 +
75 + // Test
76 + Serial.begin(9600);
77 +}
78 +
79 +//------------Functions-------------//
80 +void recvWithEndMarker() {
81 + static byte ndx = 0;
82 + char endMarker = '\n';
83 + char rc;
84 +
85 + while (wirelessSerial.available() > 0 && newData == false) {
86 + rc = wirelessSerial.read();
87 +
88 + if (rc != endMarker) {
89 + inputdata[ndx] = rc;
90 + ndx++;
91 + if (ndx >= numChars) {
92 + ndx = numChars - 1;
93 + }
94 + }
95 + else {
96 + inputdata[ndx] = '\0'; // terminate the string
97 + ndx = 0;
98 + newData = true;
99 + }
100 + }
101 + if (newData == true) {
102 + Serial.print("TESTTSETESTST ...... ");
103 + Serial.println(inputdata);
104 + Serial.println(strlen(inputdata));
105 +
106 + int inputdata_len = strlen(inputdata) - 10;
107 + Serial.print("INPUTDATALEN: ");
108 + Serial.println(inputdata_len);
109 + inputdata[inputdata_len] = '\0';
110 +
111 + Serial.println(inputdata);
112 + Serial.println(strlen(inputdata));
113 + }
114 +}
115 +
116 +void showNewData() {
117 + Serial.print("This just in ... ");
118 + Serial.println(inputdata);
119 + Serial.println(strlen(inputdata));
120 +}
121 +
122 +void ultrasonicSensor() {
123 + // Send signal
124 + digitalWrite(USTRIGPIN, LOW);
125 + delayMicroseconds(2);
126 + digitalWrite(USTRIGPIN, HIGH);
127 + delayMicroseconds(10);
128 + digitalWrite(USTRIGPIN, LOW);
129 +
130 + // Save duration(Oneway x 2)
131 + duration = pulseIn(USECHOPIN, HIGH);
132 +
133 + // Calculate distance
134 + Serial.print("Duration: ");
135 + Serial.println(duration);
136 + distance = (duration * 17) / 1000 ;
137 +
138 + // Test
139 + Serial.print("Distance: ");
140 + Serial.print(distance);
141 + Serial.println("cm");
142 +
143 + // Send thw BLE
144 + wirelessSerial.write(distance);
145 +}
146 +
147 +void temphumSensor() {
148 + // Get humidity and temperature
149 + float h = dht.readHumidity();
150 + float t = dht.readTemperature();
151 +
152 + // Test
153 + Serial.print("Humidity: ");
154 + Serial.print(h);
155 + Serial.print(" %\t");
156 + Serial.print("Temperature: ");
157 + Serial.print(t);
158 + Serial.println(" *C");
159 +
160 + // Send thw BLE
161 + wirelessSerial.write(h);
162 + wirelessSerial.write(t);
163 +}
164 +
165 +void magneticSensor() {
166 + // Get mag value
167 + mag_value = digitalRead(MAGPIN);
168 +
169 + // Test
170 + Serial.print("Magnetic: ");
171 + Serial.println(mag_value);
172 +
173 + // Send thw BLE
174 + wirelessSerial.write(mag_value);
175 +}
176 +
177 +void cycleNeoPixel() {
178 + for (int i = 0; i < NUMLED; i++) {
179 + strip.setPixelColor(i % NUMLED, 0, 0, 0);
180 + strip.setPixelColor((i + 1) % NUMLED, 0, 1, 2);
181 + strip.setPixelColor((i + 2) % NUMLED, 0, 4, 3);
182 + strip.setPixelColor((i + 3) % NUMLED, 0, 16, 9);
183 + strip.setPixelColor((i + 4) % NUMLED, 0, 30, 16);
184 + strip.setPixelColor((i + 5) % NUMLED, 0, 60, 31);
185 + strip.setPixelColor((i + 6) % NUMLED, 0, 0, 0);
186 + strip.setPixelColor((i + 7) % NUMLED, 1, 2, 0);
187 +
188 + strip.show();
189 + delay(80);
190 + }
191 +}
192 +
193 +void offNeoPixel() {
194 + for (int i = 0; i < NUMLED; i++) {
195 + strip.setPixelColor(i, 0, 0, 0);
196 + }
197 + strip.show();
198 +}
199 +
200 +void doseDisplay() {
201 + Serial.print("Dose: ");
202 + Serial.println(inputdata);
203 + Serial.println(int(inputdata[0] - '0'));
204 + for (int i = 0; i < 10; i++) {
205 + cycleNeoPixel();
206 + display.showNumberDec(int(inputdata[0] - '0'), false, 1, 3);
207 + }
208 + display.clear();
209 + offNeoPixel();
210 +}
211 +
212 +void dateDisplay() {
213 + Serial.print("Last time: ");
214 + Serial.print(inputdata[0]);
215 + Serial.print(inputdata[1]);
216 + Serial.print(inputdata[2]);
217 + Serial.println(inputdata[3]);
218 +
219 + display.showNumberDec(int(inputdata[0] - '0'), false, 1, 0);
220 + display.showNumberDec(int(inputdata[1] - '0'), false, 1, 1);
221 + display.showNumberDec(int(inputdata[2] - '0'), false, 1, 2);
222 + display.showNumberDec(int(inputdata[3] - '0'), false, 1, 3);
223 + delay(5000);
224 + display.clear();
225 +}
226 +
227 +
228 +//---------------Main----------------//
229 +void loop() {
230 + // Data
231 + if (newData == false) {
232 + recvWithEndMarker();
233 + }
234 +
235 + // Call Functions
236 + if (newData == true) {
237 + showNewData();
238 + // Menu
239 + if (inputdata[0] == 'A') {
240 + ultrasonicSensor();
241 + }
242 + else if (inputdata[0] == 'B') {
243 + temphumSensor();
244 + }
245 + else if (inputdata[0] == 'C') {
246 + magneticSensor();
247 + }
248 + else if (strlen(inputdata) < 4) {
249 + doseDisplay();
250 + } else {
251 + dateDisplay();
252 + }
253 + newData = false;
254 + }
255 +}
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "extends": "eslint:recommended",
3 + "rules": {
4 + "semi": ["warn", "never"],
5 + "quotes": ["warn", "single"],
6 + "no-console": ["off"]
7 + },
8 + "parserOptions": {
9 + "ecmaVersion": 9
10 + },
11 + "env": {
12 + "es6": true,
13 + "node": true,
14 + "browser": true,
15 + "amd": true
16 + },
17 + "globals": {
18 + "$": true,
19 + "require": true,
20 + "process": true
21 + },
22 + "root": true
23 +}
...\ No newline at end of file ...\ No newline at end of file
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
2 const User = require('../../models/user'); 2 const User = require('../../models/user');
3 const Joi = require('joi'); 3 const Joi = require('joi');
4 4
5 +
5 exports.register = async(ctx) => { 6 exports.register = async(ctx) => {
6 const { userId, password, passwordCheck } = ctx.request.body; 7 const { userId, password, passwordCheck } = ctx.request.body;
7 8
...@@ -49,7 +50,7 @@ exports.login = async(ctx) => { ...@@ -49,7 +50,7 @@ exports.login = async(ctx) => {
49 } 50 }
50 51
51 const user = await User.findByUserId(userId); 52 const user = await User.findByUserId(userId);
52 - if(!user) { 53 + if(!user || !user.userTypeCd) {
53 ctx.stauts = 401; 54 ctx.stauts = 401;
54 return; 55 return;
55 } 56 }
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
2 const Bottle = require('../../models/bottle'); 2 const Bottle = require('../../models/bottle');
3 const Hub = require('../../models/hub'); 3 const Hub = require('../../models/hub');
4 const Medicine = require('../../models/medicine'); 4 const Medicine = require('../../models/medicine');
5 +const User = require('../../models/user');
5 const Mqtt = require('../../lib/MqttModule'); 6 const Mqtt = require('../../lib/MqttModule');
6 const jwt = require('jsonwebtoken'); 7 const jwt = require('jsonwebtoken');
7 8
...@@ -14,6 +15,12 @@ exports.bottleConnect = async(ctx) => { ...@@ -14,6 +15,12 @@ exports.bottleConnect = async(ctx) => {
14 } 15 }
15 16
16 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 17 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
18 + const user = await User.findById(userId);
19 + if(!user || !user.userTypeCd) {
20 + ctx.status = 403;
21 + return;
22 + }
23 +
17 const { bottleId, hubId } = ctx.request.body; 24 const { bottleId, hubId } = ctx.request.body;
18 25
19 const isExistBottle = await Bottle.findByBottleId(bottleId); 26 const isExistBottle = await Bottle.findByBottleId(bottleId);
...@@ -62,6 +69,12 @@ exports.bottleDisconnect = async(ctx) => { ...@@ -62,6 +69,12 @@ exports.bottleDisconnect = async(ctx) => {
62 } 69 }
63 70
64 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 71 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
72 + const user = await User.findById(userId);
73 + if(!user || !user.userTypeCd) {
74 + ctx.status = 403;
75 + return;
76 + }
77 +
65 const { bottleId } = ctx.params; 78 const { bottleId } = ctx.params;
66 79
67 const bottle = await Bottle.findByBottleId(bottleId); 80 const bottle = await Bottle.findByBottleId(bottleId);
...@@ -97,6 +110,12 @@ exports.lookupInfo = async(ctx) => { ...@@ -97,6 +110,12 @@ exports.lookupInfo = async(ctx) => {
97 } 110 }
98 111
99 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 112 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
113 + const user = await User.findById(userId);
114 + if(!user || !user.userTypeCd) {
115 + ctx.status = 403;
116 + return;
117 + }
118 +
100 const { bottleId } = ctx.params; 119 const { bottleId } = ctx.params;
101 120
102 const isBottleExist = await Bottle.findByBottleId(bottleId); 121 const isBottleExist = await Bottle.findByBottleId(bottleId);
...@@ -133,6 +152,12 @@ exports.setMedicine = async(ctx) => { ...@@ -133,6 +152,12 @@ exports.setMedicine = async(ctx) => {
133 } 152 }
134 153
135 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 154 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
155 + const user = await User.findById(userId);
156 + if(!user || !user.userTypeCd) {
157 + ctx.status = 403;
158 + return;
159 + }
160 +
136 const { bottleId } = ctx.params; 161 const { bottleId } = ctx.params;
137 const { medicineId, dosage } = ctx.request.body; 162 const { medicineId, dosage } = ctx.request.body;
138 163
...@@ -173,6 +198,12 @@ exports.getBottleList = async(ctx) => { ...@@ -173,6 +198,12 @@ exports.getBottleList = async(ctx) => {
173 } 198 }
174 199
175 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 200 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
201 + const user = await User.findById(userId);
202 + if(!user || !user.userTypeCd) {
203 + ctx.status = 403;
204 + return;
205 + }
206 +
176 const { hubId } = ctx.params; 207 const { hubId } = ctx.params;
177 208
178 const hub = await Hub.findByHubId(hubId); 209 const hub = await Hub.findByHubId(hubId);
......
1 //허브(Mqtt Broker)등록 및 삭제 1 //허브(Mqtt Broker)등록 및 삭제
2 const Hub = require('../../models/hub'); 2 const Hub = require('../../models/hub');
3 +const User = require('../../models/user');
3 const Mqtt = require('../../lib/MqttModule'); 4 const Mqtt = require('../../lib/MqttModule');
4 const DataProcess = require('../../lib/DataProcess'); 5 const DataProcess = require('../../lib/DataProcess');
5 const jwt = require('jsonwebtoken'); 6 const jwt = require('jsonwebtoken');
...@@ -12,6 +13,12 @@ exports.hubConnect = async (ctx) => { ...@@ -12,6 +13,12 @@ exports.hubConnect = async (ctx) => {
12 } 13 }
13 14
14 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 15 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
16 + const user = await User.findById(userId);
17 + if(!user || !user.userTypeCd) {
18 + ctx.status = 403;
19 + return;
20 + }
21 +
15 const { hubId, host, port } = ctx.request.body; 22 const { hubId, host, port } = ctx.request.body;
16 23
17 const isExistHub = await Hub.findByHubId(hubId); 24 const isExistHub = await Hub.findByHubId(hubId);
...@@ -47,6 +54,12 @@ exports.getHubList = async(ctx) => { ...@@ -47,6 +54,12 @@ exports.getHubList = async(ctx) => {
47 } 54 }
48 55
49 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 56 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
57 + const user = await User.findById(userId);
58 + if(!user || !user.userTypeCd) {
59 + ctx.status = 403;
60 + return;
61 + }
62 +
50 const hubList = await Hub.find({ userId }); 63 const hubList = await Hub.find({ userId });
51 if(!hubList || !hubList.length) { 64 if(!hubList || !hubList.length) {
52 ctx.status = 404; 65 ctx.status = 404;
...@@ -65,6 +78,12 @@ exports.hubDisconnect = async(ctx) => { ...@@ -65,6 +78,12 @@ exports.hubDisconnect = async(ctx) => {
65 } 78 }
66 79
67 const { userId } = jwt.verify(token, process.env.JWT_SECRET); 80 const { userId } = jwt.verify(token, process.env.JWT_SECRET);
81 + const user = await User.findById(userId);
82 + if(!user || !user.userTypeCd) {
83 + ctx.status = 403;
84 + return;
85 + }
86 +
68 const { hubId } = ctx.params; 87 const { hubId } = ctx.params;
69 88
70 const hub = await Hub.findByHubId(hubId); 89 const hub = await Hub.findByHubId(hubId);
......
1 +const Router = require('koa-router');
2 +const userCtrl = require('./user.ctrl');
3 +
4 +const user = new Router();
5 +
6 +/**
7 + * 현재 유저 정보 조회
8 + * request parameter : token
9 + * url : http://localhost:4000/api/user
10 + * return : Object User
11 + */
12 +user.get('/', userCtrl.myInfo);
13 +
14 +/**
15 + * 현재 유저의 타입에 따라 요청 유저 정보 조회(의사 : 환자, 관리자 : 모든 유저)
16 + * request parameter : token
17 + * url : http://localhost:4000/api/user/:reqUserId
18 + * return : status
19 + */
20 + user.get('/:reqUserId', userCtrl.getUserDetail);
21 +
22 + /**
23 + * 현재 유저의 타입에 따라 요청 유저 정보 수정(의사 : 환자, 관리자 : 모든 유저)
24 + * request parameter : token
25 + * url : http://localhost:4000/api/user/:reqUserId
26 + * return : status
27 + */
28 +user.patch('/:reqUserId', userCtrl.updateReqUser);
29 +
1 +//유저에 관련된 Api
2 +const User = require('../../models/user')
3 +const Bottle = require('../../models/bottle')
4 +const Hub = require('../../models/hub')
5 +const jwt = require('jsonwebtoken')
6 +
7 +
8 +exports.myInfo = async ctx => {
9 + const token = ctx.req.headers.authorization
10 + if (!token || !token.length) {
11 + ctx.status = 401
12 + return
13 + }
14 +
15 + const { userId } = jwt.verify(token, process.env.JWT_SECRET)
16 + const user = await User.findById(userId);
17 + if(!user || !user.userTypeCd) {
18 + ctx.status = 403;
19 + return;
20 + }
21 +
22 + let result = {
23 + myInfo : user,
24 + myDoctor : null,
25 + patientList : [],
26 + userList : [],
27 + };
28 +
29 + if (user.userTypeCd === 'NORMAL') {
30 + const doctor = await User.findById(user.doctorId);
31 + result.myDoctor = doctor;
32 +
33 + } else if (user.userTypeCd === 'DOCTOR') {
34 + const patientList = await User.findAllByDoctorId(user.userId);
35 + result.patientList = patientList;
36 +
37 + } else if (user.userTypeCd === 'MANAGER') {
38 + const userList = await User.find();
39 + result.userList = userList;
40 + }
41 +
42 + ctx.status = 200;
43 + ctx.body = result;
44 +}
45 +
46 +exports.getUserDetail = async ctx => {
47 + const token = ctx.req.headers.authorization;
48 + if (!token || !token.length) {
49 + ctx.status = 401;
50 + return;
51 + }
52 +
53 + const { userId } = jwt.verify(token, process.env.JWT_SECRET);
54 + const user = await User.findById(userId);
55 + if(!user) {
56 + ctx.status = 403;
57 + return;
58 + } else if (user.userTypeCd === 'NORMAL') {
59 + ctx.status = 403;
60 + return;
61 + }
62 +
63 + let result = {
64 + reqUser : user,
65 + reqUserBottleList : [],
66 + };
67 +
68 + if (user.userTypeCd === 'DOCTOR') {
69 + const { reqUserId } = ctx.params;
70 + const reqUser = await User.findById(reqUserId);
71 + if (!reqUser) {
72 + ctx.status = 404;
73 + return;
74 + }
75 + if(reqUser.doctorId !== user.userId) {
76 + ctx.status = 403;
77 + return;
78 + }
79 +
80 + const reqUserHubList = await Hub.findAllByUserId(reqUserId);
81 + if(reqUserHubList && reqUserHubList.length) {
82 + const reqUserBottleList = [];
83 +
84 + await Promise.all(reqUserHubList.forEach(async hub => {
85 + const bottle = await Bottle.findAllByHubId(hub.hubId);
86 + reqUserBottleList.push(...bottle);
87 + }));
88 +
89 + result.reqUserBottleList = reqUserBottleList;
90 + }
91 +
92 + }
93 +
94 + ctx.status = 200;
95 + ctx.body = result;
96 +
97 +};
98 +
99 +exports.updateReqUser = async ctx => {
100 + const token = ctx.req.headers.authorization;
101 + if (!token || !token.length) {
102 + ctx.status = 401;
103 + return;
104 + }
105 +
106 + const { userId } = jwt.verify(token, process.env.JWT_SECRET);
107 + const user = await User.findById(userId);
108 + if(!user) {
109 + ctx.status = 403;
110 + return;
111 + }
112 +
113 + if (user.userTypeCd === 'MANAGER') {
114 + const { useYn } = ctx.request.body;
115 + const { reqUserId } = ctx.params;
116 +
117 + const reqUser = await User.findById(reqUserId);
118 + if(!reqUser) {
119 + ctx.status = 404;
120 + return;
121 + }
122 +
123 + await reqUser.setUseYn(useYn);
124 + await reqUser.save();
125 +
126 + return;
127 + }
128 +
129 + ctx.status = 200;
130 +
131 +}
...\ No newline at end of file ...\ No newline at end of file
1 -const mqtt = require('mqtt'); 1 +const mqtt = require('mqtt')
2 -const clientList = []; 2 +const clientList = []
3 3
4 exports.mqttOn = async (hosting, func) => { 4 exports.mqttOn = async (hosting, func) => {
5 const filterIndex = clientList.findIndex(client => { 5 const filterIndex = clientList.findIndex(client => {
6 return (client.options.clientId === hosting.clientId 6 return (client.options.clientId === hosting.clientId
7 && client.options.host === hosting.host 7 && client.options.host === hosting.host
8 && client.options.port === hosting.port) 8 && client.options.port === hosting.port)
9 - }); 9 + })
10 10
11 if(filterIndex === -1) { 11 if(filterIndex === -1) {
12 - const client = mqtt.connect(hosting); 12 + const client = mqtt.connect(hosting)
13 - clientList.push(client); 13 + clientList.push(client)
14 14
15 client.on('connect', () => { 15 client.on('connect', () => {
16 - console.log(`Hub connected: `, client.connected); 16 + console.log('Hub connected: ', client.connected)
17 - }); 17 + })
18 18
19 - client.on('message', async (topic, message, packet) => { 19 + client.on('message', async (topic, message) => {
20 - const result = await func(topic, message.toString()); 20 + const result = await func(topic, message.toString())
21 - console.log('\x1b[1;32msubscribe : topic', topic, 'message : ', message.toString(), '\x1b[0m'); 21 + console.log('\x1b[1;32msubscribe : topic', topic, 'message : ', message.toString(), '\x1b[0m')
22 - this.mqttPublishMessage(client, result); 22 + this.mqttPublishMessage(client, result)
23 - }); 23 + })
24 24
25 - return client; 25 + return client
26 } 26 }
27 27
28 - return clientList[filterIndex]; 28 + return clientList[filterIndex]
29 -}; 29 +}
30 30
31 exports.mqttSubscribe = (client, topic) => { 31 exports.mqttSubscribe = (client, topic) => {
32 - client.subscribe(topic); 32 + client.subscribe(topic)
33 -}; 33 +}
34 34
35 exports.mqttPublishMessage = (client, { topic, message }) => { 35 exports.mqttPublishMessage = (client, { topic, message }) => {
36 client.publish(topic, message, () => { 36 client.publish(topic, message, () => {
37 - console.log('\x1b[1;33mpublish : topic', topic, 'message : ', message, '\x1b[0m'); 37 + console.log('\x1b[1;33mpublish : topic', topic, 'message : ', message, '\x1b[0m')
38 - }); 38 + })
39 -}; 39 +}
40 40
41 exports.mqttUnsubscribe = (client, topic) => { 41 exports.mqttUnsubscribe = (client, topic) => {
42 client.unsubscribe(topic, () => { 42 client.unsubscribe(topic, () => {
43 - console.log('unsubscribe', topic); 43 + console.log('unsubscribe', topic)
44 - }); 44 + })
45 -}; 45 +}
46 46
47 exports.mqttOff = (hosting) => { 47 exports.mqttOff = (hosting) => {
48 const filterIndex = clientList.findIndex(client => { 48 const filterIndex = clientList.findIndex(client => {
49 return (client.options.clientId === hosting.clientId 49 return (client.options.clientId === hosting.clientId
50 && client.options.host === hosting.host 50 && client.options.host === hosting.host
51 && client.options.port === hosting.port) 51 && client.options.port === hosting.port)
52 - }); 52 + })
53 53
54 if(filterIndex !== -1) { 54 if(filterIndex !== -1) {
55 - clientList[filterIndex].end(); 55 + clientList[filterIndex].end()
56 - clientList.splice(filterIndex, 1); 56 + clientList.splice(filterIndex, 1)
57 } 57 }
58 } 58 }
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -7,16 +7,19 @@ const BottleSchema = new Schema ({ ...@@ -7,16 +7,19 @@ const BottleSchema = new Schema ({
7 temperature : { type : Number, default : 0 }, 7 temperature : { type : Number, default : 0 },
8 humidity : { type : Number, default : 0 }, 8 humidity : { type : Number, default : 0 },
9 balance : { type : Number, default : 0 }, 9 balance : { type : Number, default : 0 },
10 - recentOpen : { type : Date, default : Date.now },
11 medicineId : { type : Number, default : null, }, 10 medicineId : { type : Number, default : null, },
12 - hubId : Number, 11 + dosage : { type : Number, default : 0 },
13 - dosage : { type : Number, default : 0 } 12 + hubId : { type : Number, ref : 'Hub' },
14 }) 13 })
15 14
16 BottleSchema.statics.findByBottleId = function(bottleId) { 15 BottleSchema.statics.findByBottleId = function(bottleId) {
17 return this.findOne({ bottleId }); 16 return this.findOne({ bottleId });
18 }; 17 };
19 18
19 +BottleSchema.statics.findAllByHubId = function(hubId) {
20 + return this.find({ hubId });
21 +};
22 +
20 BottleSchema.methods.getBottleId = function() { 23 BottleSchema.methods.getBottleId = function() {
21 return this.bottleId; 24 return this.bottleId;
22 }; 25 };
...@@ -49,4 +52,12 @@ BottleSchema.methods.getHubId = function() { ...@@ -49,4 +52,12 @@ BottleSchema.methods.getHubId = function() {
49 return this.hubId; 52 return this.hubId;
50 }; 53 };
51 54
55 +BottleSchema.methods.setMedicineId = function(medicineId) {
56 + this.medicineId = medicineId;
57 +};
58 +
59 +BottleSchema.statics.setDosage = function(dosage) {
60 + this.dosage = dosage;
61 +};
62 +
52 module.exports = mongoose.model('Bottle', BottleSchema); 63 module.exports = mongoose.model('Bottle', BottleSchema);
...\ No newline at end of file ...\ No newline at end of file
......
1 +const mongoose = require('mongoose');
2 +
3 +const Schema = mongoose.Schema;
4 +
5 +const TakeMedicineHistorySchema = new Schema ({
6 + takeDate : {
7 + type : Date,
8 + required : true,
9 + default : Date.now,
10 + },
11 + medicineId : {
12 + type : Number,
13 + ref : 'Medicine',
14 + required : true,
15 + },
16 + bottleId : {
17 + type : Number,
18 + ref : 'Bottle',
19 + required : true,
20 + },
21 +});
22 +
23 +TakeMedicineHistorySchema.statics.findByBottleId = async function(bottleId) {
24 + return this.find({ bottleId });
25 +};
26 +
27 +TakeMedicineHistorySchema.statics.findByBottleIdAndMedicineId = async function(bottleId, medicineId) {
28 + return this.find({ bottleId, medicineId });
29 +};
30 +
31 +
32 +module.export = mongoose.model("TakeMedicineHist", TakeMedicineHistorySchema);
...\ No newline at end of file ...\ No newline at end of file
...@@ -5,13 +5,17 @@ const Schema = mongoose.Schema; ...@@ -5,13 +5,17 @@ const Schema = mongoose.Schema;
5 const HubSchema = new Schema ({ 5 const HubSchema = new Schema ({
6 hubId : { type : Number, required : true, unique : true }, 6 hubId : { type : Number, required : true, unique : true },
7 hosting : { type : Object, default : null }, 7 hosting : { type : Object, default : null },
8 - userId : { type : String, default : null }, 8 + userId : { type : String, default : null, ref : 'User' },
9 }); 9 });
10 10
11 HubSchema.statics.findByHubId = function(hubId) { 11 HubSchema.statics.findByHubId = function(hubId) {
12 return this.findOne({ hubId }) 12 return this.findOne({ hubId })
13 }; 13 };
14 14
15 +HubSchema.statics.findAllByUserId = function(userId) {
16 + return this.find({ userId });
17 +};
18 +
15 HubSchema.methods.setHubHost = function(hosting) { 19 HubSchema.methods.setHubHost = function(hosting) {
16 this.hosting = hosting; 20 this.hosting = hosting;
17 }; 21 };
......
...@@ -5,9 +5,9 @@ const Schema = mongoose.Schema; ...@@ -5,9 +5,9 @@ const Schema = mongoose.Schema;
5 const MedicineSchema = new Schema ({ 5 const MedicineSchema = new Schema ({
6 medicineId : { type : Number, required : true, unique : true }, 6 medicineId : { type : Number, required : true, unique : true },
7 name : { type : String, required : true }, 7 name : { type : String, required : true },
8 - company : String, 8 + company : { type : String, required : true },
9 target : { type : String, required : true }, 9 target : { type : String, required : true },
10 - dosage : { type : String, required : true }, 10 + dosageInfo : { type : String, required : true },
11 warn : { type : String, required : true }, 11 warn : { type : String, required : true },
12 antiEffect : { type : String, required : true } 12 antiEffect : { type : String, required : true }
13 }) 13 })
......
...@@ -4,9 +4,12 @@ const jwt = require('jsonwebtoken'); ...@@ -4,9 +4,12 @@ const jwt = require('jsonwebtoken');
4 4
5 const Schema = mongoose.Schema; 5 const Schema = mongoose.Schema;
6 6
7 -const UserSchema = new Schema({ 7 +const UserSchema = new Schema ({
8 - userId : { type: String, require : true, unique : true, lowercase : true }, 8 + userId : { type: String, required : true, unique : true, lowercase : true },
9 - hashedPassword : { type : String, default : null } 9 + hashedPassword : { type : String, required : true },
10 + userTypeCd : { type : String, required : true, default : 'NORMAL' },
11 + doctorId : { type : String, default : null },
12 + useYn : { type : Boolean, default : true },
10 }); 13 });
11 14
12 UserSchema.methods.setPassword = async function(password) { 15 UserSchema.methods.setPassword = async function(password) {
...@@ -19,10 +22,22 @@ UserSchema.methods.checkPassword = async function(password) { ...@@ -19,10 +22,22 @@ UserSchema.methods.checkPassword = async function(password) {
19 return result; 22 return result;
20 }; 23 };
21 24
25 +UserSchema.methods.setUseYn = async function(useYn) {
26 + this.useYn = useYn;
27 +}
28 +
22 UserSchema.statics.findByUserId = async function(userId) { 29 UserSchema.statics.findByUserId = async function(userId) {
23 return this.findOne({ userId }); 30 return this.findOne({ userId });
24 }; 31 };
25 32
33 +UserSchema.statics.findAllByDoctorId = async function(doctorId) {
34 + return this.find({ doctorId });
35 +};
36 +
37 +UserSchema.statics.findAllByUserTypeCd = async function(userTypeCd) {
38 + return this.find({ userTypeCd });
39 +};
40 +
26 UserSchema.methods.generateToken = function() { 41 UserSchema.methods.generateToken = function() {
27 const token = jwt.sign ( 42 const token = jwt.sign (
28 { 43 {
......